Java中last_insert_id的使用


last_insert_id的作用是:在當前表中的主鍵是自增時,插入一條新記錄的同時使用last_insert_id可以獲取當前的新記錄的主鍵id。

下面是一個例子:

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring.xml","classpath:applicationContext.xml"})
public class TestSql {
    @Autowired(required = true) 
    private JdbcTemplate jdbcTemplate; 
    @Autowired(required = true) 
    private JdbcTemplate jdbcTemplate1; 
    
    @Test
    public void select(){
        final String sql = "insert into series(class_id,brand_id,series_name) values("+2+","+2+",'"+ "sfsfds')";
        System.out.println(sql);
        
        /*
        //這種方式會出現主鍵不確定性(當在另一張表同時插入一條數據並也要獲取主鍵時會出現重復或者為0的情況)
        int ret = jdbcTemplate.update(sql);
        System.out.println("系列返回值==="+ret);
        String last = "select last_insert_id()";
        int lastId = jdbcTemplate.queryForInt(last);
        System.out.println("最新系列ID===="+lastId);
        */
        
        KeyHolder keyHolder = new GeneratedKeyHolder();  
        //這種方式是在上一種方式之上優化其不確定性(避免出現上述重復或者為0的情況)
        int i = jdbcTemplate.update(new PreparedStatementCreator() {  
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {  
                return con.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
                //or return con.prepareStatement(sql, new String[]{"ID"});//ID是自動增長的自動  
            }  
        }, keyHolder);  
        System.out.println(i);
        System.out.println(keyHolder.getKeyList());
        
        final String sql1 = "insert into meta_type(series_id,type_name) values("+2+",'"+ "sfsfds')";
        System.out.println(sql1);
//        KeyHolder keyHolder1 = new GeneratedKeyHolder();  
        int j = jdbcTemplate1.update(new PreparedStatementCreator() {  
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {  
                return con.prepareStatement(sql1, PreparedStatement.RETURN_GENERATED_KEYS);  
                //or return con.prepareStatement(sql, new String[]{"ID"});//ID是自動增長的自動  
            }  
        }, keyHolder);  
        System.out.println("----"+j);  
        System.out.println(keyHolder.getKeyList());
    }
    
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM