public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection c = DriverManager.getConnection( "jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8","root", "admin");
System.out.println("驱动加载成功");
Statement s = c.createStatement();
c.setAutoCommit(false);
String sql1 = "update hero set hp = hp+1 where id = 3";
s.execute(sql1);
String sql2 = "update hero set hp = hp-1 where id= 3";
s.execute(sql2);
c.commit();
//String name = "dashen";
//String password = "thisispassword1";
//String str = "insert hero values(null,'提莫',616,521),(null,'安妮',616,521),(null,'艾希',616,521),(null,'石头',616,521)";
// String sql = "insert into hero values(null,?,?,?)";
// PreparedStatement ps = c.prepareStatement(sql);
// for(int i = 0 ; i<1000 ;i++){
// ps.setString(1,"英雄"+i);
// ps.setFloat(2,353);
// ps.setInt(3,333);
// ps.execute();
// ResultSet rs = ps.getGeneratedKeys();
// if(rs.next()){
// int id = rs.getInt(1);
// System.out.println(id);
// }
// }
// while(rs.next()){
// int id = rs.getInt(1);
// String name = rs.getString(2);
// float hp = rs.getFloat(3);
// int demage = rs.getInt(4);
// System.out.printf("%d\t%s\t%f\t%d\n",id,name,hp,demage);
// }
}catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
事务
//事务的开始
c.setAutoCommit(false);
String sql1 = "update hero set hp = hp+1 where id = 3";
s.execute(sql1);
String sql2 = "update hero set hp = hp-1 where id= 3";
s.execute(sql2);
c.commit();
//事务的提交
如果事务中间有异常的代码,所有的都不执行。