jdbc java数据库连接 8)防止sql注入

时间:2021-06-25 16:52:27

回顾下之前jdbc的开发步骤:

  1:建项目,引入数据库驱动包

  2:加载驱动

    Class.forName(..);

  3:获取连接对象

  4:创建执行sql语句的stmt对象;  写sql

  5:执行sql

    a) 更新    delete/insert/update

      !:executeUpdate();

    b) 查询    select  

      !:executeQuery();

  6:关闭/异常

之前有说过,Statement接口和PreparedStatement接口的区别,其中的一个就是:

  PreparedStatement接口能够防止sql注入

那么,什么是sql注入呢?

  其实sql注入就是用户输入的恶意密码,能够绕过你的用户名和密码登陆。

例子:

  1:首先创建个数据库

 -- 创建数据库
CREATE DATABASE jdbc_demo DEFAULT CHARACTER SET utf8;i
-- 创建表
USE jdbc_demo;
CREATE TABLE admin(
id INT PRIMARY KEY AUTO_INCREMENT,
userName VARCHAR(20),
pwd VARCHAR(20)
)

  

  2:使用Statement接口,没有防止sql注入:

 /**
* 模拟用户登陆数据库,演示注入
*
* @author LLZ
*/
public class Two_StatementDemo { /**
* 1:sql注入 Statement
*/ private Connection conn;
private Statement stsm;
private ResultSet rs;
private PreparedStatement pstsm; @Test
public void Test1() { String user = "tom";
// String password = "123";
String password = " ' or 1=1 -- /**/ "; // sql注入,这个也可以登陆成功 try {
// 1.1:加载驱动
conn = Jdbcutil.getConnection(); // 1.3:创建Statement对象
stsm = conn.createStatement(); // 1.4:准备sql语句
String sql = "select * from jdbc where user='" + user
+ "' and password='" + password + "' "; // 1.5:执行sql
rs = stsm.executeQuery(sql); // 1.6:打印返回的结果
if (rs.next()) {
System.out.println(rs.getInt("id"));
}
} catch (Exception e) {
e.printStackTrace(); } finally {
// 1.7:关闭连接
try {
rs.close();
stsm.close();
conn.close();
} catch (Exception e) { e.printStackTrace();
}
}
}

  3:使用PreparedStatement接口,防止sql注入:

其原因就是由于该接口具有缓存区,需要先执行预编译远,等传入参数才正式执行sql语言

 /**
* 二:用PreparedStatement防止sql注入
*/
@Test
public void Test2() { String user = "tom";
String password = "123";
// String password = " ' or 1=1 -- /**/ "; // sql注入,这个在这里就无法登陆
// 准备sql预编译语句
String sql = "select * from jdbc where user=? and password=?"; try {
// 2.1:创建连接
conn = Jdbcutil.getConnection(); // 2.2:创建PerparedStatement对象(执行预编译)
pstsm = conn.prepareStatement(sql); // 2.3:准备参数
pstsm.setString(1, user);
pstsm.setString(2, password); // 2.4:发送参数,执行sql
ResultSet rs = pstsm.executeQuery();
if (rs.next()) {
System.out.println(rs.getInt("id"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 2.5:关闭连接
Jdbcutil.close(conn, pstsm, rs);
} }