String sql="insert into user(u_name,password,create_time) values(?,?,?)";
1.获取自动生成的主键:
如果要获取自动生成的主键,要如下创建preparedStatment
PreparedStatement stmt = connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
而一般的声明则如下:
stmt.executeUpdate(sql,Statement.RETURN_GENERATED_KEYS);
自增主键就算事务没有提交也会生成.
2.批量更新
要在preparedStatement 中使用批量更新:
在PreparedStatement 添加完参数之后,要调用
stmt.addBatch();
而非stmt.addBatch(sql);
因为这个会直接执行语句 insert into user(u_name,password,create_time) values(?,?,?);而非preparedstatement 了.
jdk 中addBatch() 解释如下:
Adds a set of parameters to this PreparedStatement object’s batch of commands.
3.开启事务的位置
con.setAutoCommit(false);
无论是在stmt.addBatch(); 之前开启事务,还是在 int[] counts=stmt.executeBatch();的前一句开启事务都无关紧要.
数据库都会在insert 之前 执行SET autocommit=0;
但是不能在int counts=stmt.executeBatch(); 之后才(开启事务)关闭自动提交