Java中last_insert_id的使用,javalast_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()); } }