(四十七)Statement、PreparedStatement、CallableStatement有什么区别

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jiangshangchunjiezi/article/details/88253817

JDBC:

Statement(接口)
     |
PreparedStatement(接口)
     |
CallableStatement(接口)
以上三者为继承关系。

一、Statement

用于执行不带参数的简单SQL语句,每次执行SQL语句,数据库都要执行SQL语句的编译,最好用于仅执行一次查询并返回结果情形,效率高于PreparedStatement

            stmt=con.createStatement();
            stmt.execute("insert into employee values(1,'jim1',25)");
			rs=stmt.executeQuery("select * from employee");
			while(rs.next())
			{
				System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getInt(3));
			}

二、PreparedStatement:预编译的SQL语句的对象

执行的SQL语句中是可以带参数的,并支持批量执行SQL。

由于采用cache机制,则预先编译的语句,就会放在cache中,下次执行相同SQL语句,则直接从cache中取出来

con=DriverManager.getConnection(url,user,password);
				pstmt=con.prepareStatement("update employee set age=? where id=?");
				pstmt.setInt(1, 30);
				pstmt.setInt(2, 3);
				pstmt.executeUpdate();

三、CallableStatement 

提供了用来调用数据库中存储过程的接口,如果有输出参数要注册,说明是输出参数

四、PreparedStatement与Statement区别

①代码可读性和可维护性更好

            int id=4;
			String name="jim4";
			int age=24;
			stmt.execute("insert into employee values('"+id+"','"+name+"','"+age+"')");

②安全性更好

在SQL中有万能钥匙'OR 1='1,在Statement中是将参数直接放入SQL语句中连接到一起执行

String name="jim4 'OR 1='1";
			
rs=stmt.executeQuery("select * from employee where name='"+name+"'");

在PreparedStatement中,是将jim4 'OR 1='1作为一个字符串赋值给?,作为name字段对应的值,显然这样注入就无从谈起了

③效率更高

每一种数据库都会尽最大努力对预编译语句提供最大的性能优化,因为预编译语句有可能会被重复调用。当下次调用时无需编译,只要将参数直接传入编译过的语句执行代码中就会执行。

参考:https://blog.csdn.net/xiaodanjava/article/details/8127805

https://ych0108.iteye.com/blog/2201319

猜你喜欢

转载自blog.csdn.net/jiangshangchunjiezi/article/details/88253817