PreparedStatement对象

简介: PreparedStatement对象

PreperedStatement是Statement的子类,它的实例对象可以通过调用 Connection.preparedStatement()方法获得,相对于Statement对象而言:PreperedStatement可以避 免SQL注入的问题。

Statement会使数据库频繁编译SQL,可能造成数据库缓冲区溢出。

PreparedStatement可对SQL进行预编译,从而提高数据库的执行效率。并且PreperedStatement对于 sql中的参数,允许使用占位符的形式进行替换,简化sql语句的编写。

使用PreparedStatement对象完成对数据库的CRUD操作


查询防止sql注入

public class TestSelect {
    public static void main(String[] args) {
        login("lisi","123456");
    }
    public static void login(String name ,String password) {
        Connection co=null;
        PreparedStatement pr = null;
        ResultSet rs=null;
        try {
            co = JdbcUtils.getConnection();
            String sql = "select * from users where `name`=? and `password`= ? ";
            pr = co.prepareStatement(sql);
            pr.setObject(1,name);
            pr.setObject(2,password);
            rs = pr.executeQuery();
            while (rs.next()){
                System.out.println(rs.getString("name"));
                System.out.println(rs.getString("password"));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JdbcUtils.release(co,pr,rs);
        }
    }
}


原理:执行的时候参数会用引号包起来,并把参数中的引号作为转义字符,从而避免了参数也作为条件 的一部分


相关文章
|
SQL Java 关系型数据库
|
SQL 安全
Java-PreparedStatement对象
Java-PreparedStatement对象 与Statement对象的区别 引入PreparedStatement对象是因为使用Statement对象容易被SQL注入,而PreparedStatement对象采用了预编译的方法,会对传入的参数进行强制类型检查和安全检查,进而避免了SQL注入的产生,使得操作更加安全(具体见博客内的文章SQL注入简介) 操作方法
使用PreparedStatement实现CRUD操作
使用PreparedStatement实现CRUD操作
36 0
PreparedStatement 防止 SQL 注入原理
PreparedStatement 对象可以防止 SQL 注入,而 Statement 对象不能防止 SQL 注入,接下来使用一个案例剖析原理。
PreparedStatement 防止 SQL 注入原理
|
容器
prepareEnvironment
prepareEnvironment
65 0
|
Java 数据库连接
使用JDBC中的PreparedStatement批量插入
使用JDBC中的PreparedStatement批量插入
324 0
|
SQL 缓存 Java
数据库连接关闭工具类、Statement介绍、PreparedStatement介绍及区别
数据库连接关闭工具类、Statement介绍、PreparedStatement介绍及区别
110 0
|
SQL Java 关系型数据库
PreparedStatement 的用法 | 学习笔记
快速学习 PreparedStatement 的用法。
259 1
|
Java 关系型数据库 MySQL
JDBC学习(八):PreparedStatement实现数据的批量插入
JDBC学习(八):PreparedStatement实现数据的批量插入
279 0
浅析 PreparedStatement 和 Statement
PreparedStatement 和 Statement的创建方法、执行方法、返回结果和关闭连接
浅析 PreparedStatement 和 Statement