/*
*
* sql注入:数据库对用户传入的参数进行了编辑,改变了原本的sql的结构
* 预编译:在用户传入参数之前先进行编译,确定sql的结构,在传入用户的参数执行
* 1.select count(*) from user where username = ? and password = ?;
* 对于参数部分使用占位符?
* 2.编译完毕之后,确定了结构才传入参数
* 3.对于用户传入的特殊字符参数,使用转义,变成没有实际意义的字符
*
* 预编译操作对象的获取api:
* PreparedStatement prepareStatement(String sql) 创建一个 PreparedStatement对象,用于将参数化的SQL语句发送到数据库。
* */
1.executeQuery()方法,主要用DQL语句
public class LoginDemo {
public static void main(String[] args) throws SQLException {
Connection connection = JdbcUtil.getConnection();
String sql = "SELECT count(*) FROM USER WHERE username = ? AND password = ? ;";
//1.在用户传入参数之前先进行编译,确定sql的结构
PreparedStatement statement = connection.prepareStatement(sql);
//2.预编译完毕之后,再传入用户的参数
statement.setString(1,username);
statement.setString(2,password);
//3.执行sql即可
ResultSet resultSet = statement.executeQuery(); //注意:预编译时,sql不用再传,之前已经传递过了
int count = 0;
while (resultSet.next()) {
count = resultSet.getInt("count(*)");
}
System.out.println(count >0 ? "登录成功" :" 登录失败");
JdbcUtil.release(resultSet,statement,connection);
}
}
2.executeUpdate()方法,主要用于DML语句(update,delete,insert)
public class CRUDDemo {
@Test
public void insertTest() throws SQLException {
Connection connection = JdbcUtil.getConnection();
//使用预编译进行数据的插入
String sql = "INSERT into USER VALUES (?,?,?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1,6);
statement.setString(2,"liubei");
statement.setString(3,"123456");
int executeUpdate = statement.executeUpdate();
System.out.println(executeUpdate);
JdbcUtil.release(null,statement,connection);
}
}