首页 > 开发 > Java > 正文

JDBC中Statement和Preparement的使用讲解

2019-10-21 18:41:47
字体:
来源:转载
供稿:网友

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创建一个StatementStatement 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创建一个PreparedStatementPreparedStatement 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

运行结果:

JDBC,Statement,Preparement

二.安全方面

又因为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注入,提高安全性

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对CuoXin错新网的支持。


注:相关教程知识阅读请移步到JAVA教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表