SQL注入问题:
用户 输入的内容作为了SQL语句语法的一部分,改变了原有SQL真正的意义。
当用户输入密码为: or 1=1 时 , 用户名和密码是什么已经不重要了 , 因为1=1相当于是true , OR关系有一个条件满足 , 用户就会永远登录成功了 .
例: SELECT * FROM users WHERE username=‘a’ AND PASSWORD=‘2’ OR 1=1;
所以: 我们可以使用PreparedStatement来解决这个问题 .
preparedStatement:
预编译对象 , 是Statement对象的子类. 比Statement 效率高 .
我们可以把每条sql语句中所有的 实际参数, 都必须使用 占位符 ? . 代替.
例 : select * from user where username = ? and password = ? ;
使用步骤:
1.获取预编译对象
/ / 参数传入已经使用占位符处理后的SQL语句.
PreparedStatemen psmt = conn.preparedStatement(sql) ;
2.设置实际参数
setXxx(int index , Xxx xx) 将指定参数设置指定类型的值.
一般使用setObject( ) , 可以存放所有的类型 .
例: setObject( 1 , “用户名” ) ; 第一个位置的 ? 替换为"用户名";
注意: 有几个?占位符就要调用几次setObject方法设置值.
3.执行SQL语句.
int executeUpdate( ): / / 执行 DML语句.
ResultSet executeQuery( ): / / 执行DQL语句.
注意 : () 里 不传参数 .
/*
使用PreparedStatement对象实现增删改查
*/
public class Demo03PreparedStatementCURD {
// 使用PreparedStatement对象对数据进行添加
@Test // 进行单元测试 .
public void testInsert() throws SQLException {
// 1. 使用JDBCUtils工具类获取Collection
Connection conn = JDBCUtil.getConnection();
// 2. 获取预编译的执行者对象preparedStatement
String sql = "insert into users(username , password) values(?,?)";
PreparedStatement pst = conn.prepareStatement(sql);
// 3. 设置占位符的实际参数 .
pst.setObject(1,"老王");
pst.setObject(2,"123");
// 4. 执行sql语句 .
int i = pst.executeUpdate();
System.out.println(i+"行数据添加成功...");
// 5. 释放资源
JDBCUtil.close(null , pst , conn);
}
// 使用PreparedStatement对象对数据进行删除
@Test
public void testDelete() throws SQLException {
// 1. 使用JDBCUtils获取数据库连接对象.
Connection conn = JDBCUtil.getConnection();
// 2. 获取预编译对象preparedStatement
String sql = "DELETE from users where uid = ? ";
PreparedStatement pst = conn.prepareStatement(sql);
// 3. 设置占位符的实际参数 .
pst.setObject(1 , 1);
// 4. 执行sql语句.
int i = pst.executeUpdate();
System.out.println(i+"行数据删除成功..");
// 5. 释放资源
JDBCUtil.close(null , pst ,conn);
}
// 使用PreparedStatement对象对数据进行更改
@Test
public void testUpdate() throws SQLException {
// 1. 使用JDBCUtils工具类获取Connection
Connection conn = JDBCUtil.getConnection();
// 2. 获取预编译对象preparedStatement
String sql = "update users set password = ? where uid = ?; ";
PreparedStatement pst = conn.prepareStatement(sql);
// 3. 设置占位符的实际参数
pst.setObject(1 , "888");
pst.setObject(2 , 2);
// 4. 执行sql语句.
int i = pst.executeUpdate();
System.out.println(i+"行数据更改成功...");
// 5. 释放资源
JDBCUtil.close(null , pst , conn);
}
// 使用PreparedStatement对象对数据进行更改
@Test
public void testSelect() throws SQLException {
//1 .使用JDBCUtils工具类获取Connection
Connection conn = JDBCUtil.getConnection();
// 2. 获取预编译对象
String sql = "select * from users; ";
PreparedStatement pst = conn.prepareStatement(sql);
// 3. 执行sql语句.
ResultSet rs = pst.executeQuery();
// 处理结果集.
while (rs.next()){
System.out.println(
rs.getInt("uid")+"\t"
+rs.getString("username")+"\t"
+rs.getString("password"));
}
// 释放资源
JDBCUtil.close(rs , pst ,conn);
}
}
JDBCUtils工具类 :
https://blog.youkuaiyun.com/qq_42986107/article/details/82770771