Connection功能
获取执行SQL的对象
- 普通执行SQL对象:Statement createStatement()
- 预编译SQL的执行SQL对象,防止SQL注入:PreparedStatement prepareStatement(sql)
- 执行存储过程的对象:CallableStatement prepareCall(sql)
事务管理
- 开启事务:setAutoCommit(boolean autoCommit),true为自动提交,false为手动提交
- 提交事务:commit()
- 回滚事务:rollback()
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
48package com.sympa.lesson01;
import javax.swing.plaf.nimbus.State;
import java.sql.*;
//我的第一个JDBC程序
public class JdbcFirstDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1.加载驱动
//Class.forName("com.mysql.cj.jdbc.Driver"); //固定写法,加载驱动
//2.用户信息和url
String url = "jdbc:mysql://127.0.0.1:3306/jdbcstudy?serverTimezone=UTC&userUnicode=true&characterEncoding=utf8&useSSL=false";
String username = "root";
String password = "";
//3.连接成功,数据库对象 Connection 代表数据库
Connection connection = DriverManager.getConnection(url, username, password);
//4.执行SQL的对象
Statement statement = connection.createStatement();
String sql = "select * from users";
String sql1 = "update users set password = 114514 where id = 1";
ResultSet resultSet = null; //返回的结果集
try {
//开启事务
connection.setAutoCommit(false);
int resultSet1 = statement.executeUpdate(sql1);
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
System.out.println("id=" + resultSet.getObject("id"));
System.out.println("name=" + resultSet.getObject("name"));
System.out.println("password=" + resultSet.getObject("password"));
System.out.println("email=" + resultSet.getObject("email"));
System.out.println("birthday=" + resultSet.getObject("birthday"));
}
//提交事务
connection.commit();
} catch (Exception e) {
//回滚事务
connection.rollback();
e.printStackTrace();
}
//5.释放连接
resultSet.close();
statement.close();
connection.close();
}
}