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()); } }
每日积累一点,都是进步的见证。