tonglin0325的个人主页

Java数据库——事务处理

 

在数据库中执行5条SQL语句,这些SQL语句本身需要保持一致,即要么同时成功,要么同时失败

事务基本操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Scanner;

public class JDBC20_demo {

//定义MySQL的数据库驱动程序
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
//定义MySQL数据库的连接地址
public static final String DBURL = "jdbc:mysql://localhost:3306/mysql_demo";
//MySQL数据库的连接用户名
public static final String DBUSER = "root";
//MySQL数据库的连接密码
public static final String DBPASS = "123456";

public static void main(String[] args) throws Exception{
// TODO 自动生成的方法存根

Connection conn = null; //数据库连接
Statement stmt = null; //数据库操作

Class.forName(DBDRIVER); //加载驱动程序
//连接MySQL数据库时,要写上连接的用户名和密码
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
conn.setAutoCommit(false); //取消自动提交
//实例化PreparedStatement
stmt = conn.createStatement(); //实例化对象
//加入5条SQL语句
stmt.addBatch("INSERT INTO user(name,password,age,sex,birthday)"+"VALUES('lisi','lisimima',14,'男','1987-09-23')");
stmt.addBatch("INSERT INTO user(name,password,age,sex,birthday)"+"VALUES('lisi','lisimima',14,'男','1987-09-23')");
stmt.addBatch("INSERT INTO user(name1,password,age,sex,birthday)"+"VALUES('lisi','lisimima',14,'男','1987-09-23')");
stmt.addBatch("INSERT INTO user(name,password,age,sex,birthday)"+"VALUES('lisi','lisimima',14,'男','1987-09-23')");
stmt.addBatch("INSERT INTO user(name,password,age,sex,birthday)"+"VALUES('lisi','lisimima',14,'男','1987-09-23')");
try{
int temp[] = stmt.executeBatch(); //批量执行
System.out.println("更新了"+temp.length+"条数据。");
conn.commit(); //提交事务
}catch(Exception e){
try{
conn.rollback();
}catch(Exception ex){
ex.printStackTrace();
}
}
stmt.close();
conn.close();
}

public static void print(ResultSet rs,int re) throws Exception{
if(re>0){
rs.next(); //由前向后输出
}else{
rs.previous(); //有后向前输出
}
int id = rs.getInt(1);
String name = rs.getString(2);
String pass = rs.getString(3);
int age = rs.getInt(4);
String sex = rs.getString(5);
java.util.Date d = rs.getDate(6);
System.out.println("编号:"+ id);
System.out.println("姓名:"+name);
System.out.println("密码:"+pass);
System.out.println("年龄:"+age);
System.out.println("性别:"+sex);
System.out.println("生日:"+d);
}
}