后期都会使用PreparedStatement
效率高,安全
5.PreparedStatement
:执行sql的对象
- SQL注入问题:在拼接sq1时,有一些sql的特殊关键字参与字符串的拼接。会造成安全性问题
如上个练习,输入用户随便,输入密码:a’or’a’='a,会显示密码正确 - SQL注入问题解决:
PreparedStatement
- 使用
PreparedStatement
步骤 :
package JDBC;
import util.JDBCutil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;
public class DmeoPassword2 {
public static void main(String[] args) throws Exception {
boolean flag = true;
while (flag) {
Scanner sca = new Scanner(System.in);
System.out.println("输入用户名");
String userIn = sca.next();
System.out.println("输入密码");
String passwordIn = sca.next();
Connection conn = JDBCutil.connection();
//String sql = "SELECT * FROM USER where username = "+"'"+userIn+"'"+"and password = "+"'"+passwordIn+"'";
String sql = "SELECT * FROM USER where username = ? and password = ?";
//Statement stmt = conn.createStatement();
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1,userIn);
stmt.setString(2,passwordIn);
//ResultSet res = stmt.executeQuery(sql);
ResultSet res = stmt.executeQuery();
if (res.next()){
System.out.println("密码正确");
flag=false;
}else {
System.out.println("密码错误");
}
JDBCutil.close(stmt, conn, res);
}
}
}