预编译Statement优点
执行效率高 由于预编译语句使用占位符 ”?”,在执行SQL之前语句会被先发送到Oracle服务器进行语法检查和编译等工作,并将SQL语句加入到Oracle的语句缓冲池里,随后再对SQL语句中的占位符”?”设置定值。 那么也就说如果你要执行1000行插入的时候第一次先SQL语句发送给Oracle服务器处理,接着以后只传递值给占位符就可以了。 因此它不需每次传递大量的SQL语句也无需对每条SQL语句做语法检查和编译所以比较高效。安全,可防止SQL注入攻击
复制//用户登录的时候,假设有下面的语句
select *
from student
where username=
'' and password=
''
//写为字符串为
String sql =
"select * from student where username='"+username+
"' and password='+password+"'"
//用户如果输入' or 1=
1
//对应的
SQL语句
select *
from student
where username=
'' or 1 =
1
//上面这句
SQL等同于下面
select *
from student
Statement执行过长语句,拼接字符串很繁琐,容易出错
使用
1.创建预编译语句对象
通过Connection对象来穿件一个预编译语句的对象
复制PrepareStatement ps = conn.prepareStatement("
select *
from student
where num = ?
and name = ?
")
2.设置占位符的内容
占位符的索引从1开始,使用setXxx方法,数据要跟列的数据对应 Void setXxx((int parameterIndex, Xxx value); Xxx表示相应的数据类型。 设置点位符位置的值,第一个参数是 1,第二个参数是 2,…..
复制
ps.setInt(
1,
12);
ps.setString(
2,
"张三");
3.执行
复制- `boolean
execute()
`
在此 PreparedStatement 对象中执行 SQL 语句,该语句可以是任何种类的 SQL 语句。
- `ResultSet executeQuery()
`
在此 PreparedStatement 对象中执行 SQL 查询,并返回该查询生成的 ResultSet 对象。
- `int executeUpdate()
`
在此 `PreparedStatement
` 对象中执行 SQL 语句,该语句必须是一个 SQL 数据操作语言(Data Manipulation Language,DML)语句
比如 `INSERT`、`UPDATE` 或 `DELETE` 语句;
或者是无返回内容的 SQL 语句,比如 `DDL` 语句。
返回一个已修改数据库中的数据数目数
```
ps.executeQuery();
```
Statement与PrepareStatement比较
StatementPreparedStatement创建语句对象的方法Connection.createStatement( )Connection.preparedStatement( sql )查询executeQuery( sql ) 要提供SQL语句executeQuery( ) 不提供提供SQL语句,但随后要设置占位符的值插入、更新、删除executeUpdate( sql ) 要提供SQL语句executeUpdate( ) 不提供提供SQL语句执行语句execute()execute()
转载于:https://www.cnblogs.com/chaoyang123/p/11549368.html