批处理
先赋予表能进行批处理的请求权限
connection = DriverManager.getConnection(
"jdbc:mysql:///test?rewriteBatchedStatements = true","root","123456");
//问号后面就是批处理的请求
ps = connection.prepareStatement(
"insert into t_user(username) values(connect('badmin' , ?))");
for (int i = 1; i<10000; i++){
ps.setObject(1,i);
ps.addBatch();//添加到批次
}
ps.executeBatch();批次一次性提交
获取自增id
ps.executeUpdate(); ResultSet rs = ps.getGeneratedKeys(sql, statement.RETURN_GENERATED_KEYS);//只有这个常量设置上了才能返回id rs.next();
事务处理
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","123456");
con.setAutoCommit(false);
ps = con.prepareStatement("select price from t_book where bid =1");
rs = ps.executeQuery();
rs.next();
double price = rs.getDouble(1);
ps = con.prepareStatement("update t_user set balance = balance - ? where id = 1");
ps.setObject(1, price);
ps.executeUpdate();
ps = con.prepareStatement("update t_book set stock = stock - 1, sales = sales +1 where bid = 1");
ps.executeUpdate();
con.commit();
} catch (Exception e) {
e.printStackTrace();
try {
con.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}finally{
JDBCUtils.close(rs,ps,con);
}