statement和preparement JDBC中Statement和Preparement的使用讲解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

statement和preparement JDBC中Statement和Preparement的使用讲解

sdr_zd   2021-03-30 我要评论

Statement对象是用来执行SQL语句的

PreparedStatement:预编译的Statement对象,是Statement的子接口。

一.性能和代码编写的简洁程度方面

它允许数据库预编译SQL语句(这些SQL语句通常有带有参数),以后每次只需改变SQL命令的参数,避免数据库每次都需要编译SQL语句,提高了性能。 e.g. 连接数据库部分

//已定义好driver、url、user、passwd等
//加载驱动
Class.forName(driver);
//获得连接
Connection conn = DriverManager.getConnection(url, user, passwd);

Statement:

//用Connection创建一个Statement
Statement stmt = conn.createStatement() {
  //100条SQL语句来插入100条记录
  for(int i = 0;i < 100;i++) {
    stmt.executeUpdate("insert into student values(" + "null, 'aaa" + i + "',90)");
  }
}

PreparedStatement:

//用Connection创建一个PreparedStatement
PreparedStatement pstmt = conn,getPreparedStatement("insert into student_table values(null, ?, 90)") {
  //设置参数,100次传入参数而不是100次传入SQL语句
  for(int i = 0;i < 100;i++) {
    pstmt.setString(1, "姓名" + i);
  //执行
  pstmt.executeUpdate();
  }
}

通过运行以上的代码可以发现,PreparedStatement插入100条记录所用的时间比Statement插入100条记录所花费时间少。而且可以在代码中可以看出,带有参数的SQL语句,创建Statement对象需要对参数进行拼接,但是PreparedStatement会简洁很多。

完整代码移步GitHub:Statement&PrepareStatement

运行结果:

二.安全方面

又因为PreparedStatement不需要拼接,还可以防止SQL注入从而提高安全性

注:SQL注入是一种Cracker入侵方式,从SQL语句的漏洞入侵

比如一个登录页面,我们在获取表单传来的参数,将其与数据库中的数据进行比对,比对有该账号密码时则登录成功:

Statement:

//传入参数username和passwd是提交的信息
String sql = "select * from users " + "where username = ' " + username + " ' and password= ' " + passwd + " ';
rs = stmt.executeQuery(sql);

如果在username框中输入了:'or true or',那么,拼接后的SQL语句就变成了:

select * from users where username = ' ' or true or ' ' and desc = ' ';

结果为true被SQL当成直接量那么直接会登录成功

PreparedStatement:

//传入参数username和passwd是提交的信息
PreparedStatement pstmt = conn.getPreparedStatement("select * from users where username = ? and password= ?");
pstmt.setString(1, username);
pstmt.setString(2, passwd);

从上述可以看出PreparedStatement相较于Statement有三个好处:

  • 1. 预编译,性能较好
  • 2. 不用拼接,易编写易读懂
  • 3. 防止SQL注入,提高安全性

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们