好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

JDBC中Statement和Preparement的使用讲解

statement对象是用来执行sql语句的

preparedstatement:预编译的statement对象,是statement的子接口。

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

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

?

1

2

3

4

5

//已定义好driver、url、user、passwd等

//加载驱动

class .forname(driver);

//获得连接

connection conn = drivermanager.getconnection(url, user, passwd);

statement:

?

1

2

3

4

5

6

7

//用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:

?

1

2

3

4

5

6

7

8

9

//用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:

?

1

2

3

//传入参数username和passwd是提交的信息

string sql = "select * from users " + "where username = ' " + username + " ' and password= ' " + passwd + " ';

rs = stmt.executequery(sql);

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

?

1

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

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

preparedstatement:

?

1

2

3

4

//传入参数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注入,提高安全性

总结

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

原文链接:https://blog.csdn.net/sdr_zd/article/details/79197491

查看更多关于JDBC中Statement和Preparement的使用讲解的详细内容...

  阅读:9次