0%

PreparedStatement对象

  • 继承于Prepared类
  • 作用:预编译SQL语句并执行,预防SQL注入问题
  • SQL注入是通过操作输入来修改事先定义好的SQL语句,用以达到代码对服务器进行攻击的方法

原理:

  1. 在获取PreparedStatement对象时,将sql语句发送给mysql服务器进行检查,编译
  2. 执行时就不用进行这些步骤,速度更快
  3. 如果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
package com.sympa.lesson01;

import javax.swing.plaf.nimbus.State;
import java.sql.*;

public class JdbcFirstDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1.加载驱动
//Class.forName("com.mysql.cj.jdbc.Driver"); //固定写法,加载驱动
//2.用户信息和url
//在url中添加useServerPrepStmts=true开启预编译功能
String url = "jdbc:mysql://127.0.0.1:3306/jdbcstudy?serverTimezone=UTC&useSSL=false&useServerPrepStmts=true";
String username = "root";
String password = "";
//3.连接成功,数据库对象 Connection 代表数据库
Connection connection = DriverManager.getConnection(url, username, password);

String sql = "select * from users";
String sql1 = "update users set password = ? where id = ?";
PreparedStatement pstmt = connection.prepareStatement(sql);
PreparedStatement pstmt1 = connection.prepareStatement(sql1);
pstmt1.setInt(1, 23333);
pstmt1.setInt(2, 1);

ResultSet resultSet = null; //返回的结果集
try {
//开启事务
connection.setAutoCommit(false);
int resultSet1 = pstmt1.executeUpdate();
resultSet = pstmt.executeQuery();
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();
pstmt.close();
pstmt1.close();
connection.close();
}
}
------ THEEND ------

欢迎关注我的其它发布渠道