jdbc的事务开启
时间:2021-07-01 10:21:17
帮助过:60人阅读
package com.xyyz.jdbc;
2
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.sql.PreparedStatement;
6 import java.sql.ResultSet;
7
8 import com.xyyz.utils.JDBCUtils;
9
10 public class JDBCDemo {
11
12 public static void main(String[] args)
throws Exception {
13 query();
14 insert();
15 query();
16 update();
17 query();
18 delete();
19 query();
20 }
21
22 /**
23 * 查询代码
24 *
25 * @throws Exception
26 */
27 public static void query()
throws Exception {
28 Connection connection =
JDBCUtils.getConnection();
29 // 获取数据库连接
30 String sql = "select * from jdbctestdata"
;
31 // 获取预编译对象
32 PreparedStatement prepareStatement =
connection.prepareStatement(sql);
33 // 执行sql语句
34 ResultSet resultSet =
prepareStatement.executeQuery();
35 // 遍历打印sql语句
36 while (resultSet.next()) {
37 System.out.println(resultSet.getInt(1) + "--" + resultSet.getString(2
));
38 }
39 // 关闭释放资源
40 JDBCUtils.closeAll(resultSet, prepareStatement, connection);
41 }
42
43 /**
44 * 插入数据
45 */
46 public static void insert()
throws Exception {
47 // 获取数据库连接
48 Connection connection =
JDBCUtils.getConnection();
49 // 这里开启了事务,最后提交了,成功的插入了一条数据。
50 connection.setAutoCommit(false);
51 String sql = "insert into jdbctestdata value(?,?,?)"
;
52 // 获取预编译对象
53 PreparedStatement prepare =
connection.prepareStatement(sql);
54 prepare.setString(1, "6"
);
55 prepare.setString(2, "小白"
);
56 prepare.setString(3, "30"
);
57 int i =
prepare.executeUpdate();
58 connection.commit();
59 System.out.println("i=" +
i);
60 // 关闭释放资源
61 JDBCUtils.closeAll(
null, prepare, connection);
62 }
63
64 /**
65 * 更新数据
66 */
67 public static void update()
throws Exception {
68
69 // 获取数据库连接
70 Connection connection =
JDBCUtils.getConnection();
71 // 这里开启了事务,但是没有提交,所以最后的执行的修改没有用。
72 connection.setAutoCommit(false);
73 String sql = "update jdbctestdata set name=? , age=? where id=?"
;
74 // 获取预编译对象
75 PreparedStatement prepare =
connection.prepareStatement(sql);
76 prepare.setString(1, "小红"
);
77 prepare.setString(2, "20"
);
78 prepare.setString(3, "6"
);
79 int i =
prepare.executeUpdate();
80 System.out.println("i=" +
i);
81 // 执行sql语句
82 JDBCUtils.closeAll(
null, prepare, connection);
83 }
84
85 /**
86 * 删除数据
87 */
88 public static void delete()
throws Exception {
89 // 获取数据库连接
90 Connection connection =
JDBCUtils.getConnection();
91 String sql = "delete from jdbctestdata where id = ?"
;
92 // 获取预编译对象
93 PreparedStatement prepare =
connection.prepareStatement(sql);
94 prepare.setString(1, "6"
);
95 int i =
prepare.executeUpdate();
96 System.out.println("i=" +
i);
97 // 执行sql语句
98 JDBCUtils.closeAll(
null, prepare, connection);
99 }
100
101 }
jdbc的事务开启
标签:语句 ring manage select 修改 port 小白 sel cte