简单概述:
PreparedStatement继承自Statement,但比Statement功能强大的多。
优点:
1、PreparedStatement是预编译的,比Statement速度快。
当同时要执行多条相同结构sql语句时使用,这时可以用setObject(),addBatch()和executeBatch()这几个函数。
2、可以防止sql注入。
对JDBC而言,SQL注入攻击只对Statement有效,对PreparedStatement是无效的,这是因为PreparedStatement不允许在插入时改变查询的逻辑结构.
举例分析:
例一: 说明PreparedStatement速度快
插入两条语句只需编译一次,而Statement则需要编译两次。
package com;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class TestPreparedStatement {
public
static void main(String[] args) {
Connection con = null;
PreparedStatement pst = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url =
"jdbc:sqlserver://127.0.0.1:1433;databaseName=userManager";
con = DriverManager.getConnection(url, "as", "");
String sql = "insert into myuser (userName,pwd) values (? ,
?)";
pst = con.prepareStatement(sql);
pst.setString(1, "张三"); //也可以用setObject()
pst.setString(2, "123");
pst.addBatch();
pst.setString(1, "李四");
pst.setString(2, "456");
pst.addBatch();
pst.executeBatch();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (pst != null) {
pst.close();
pst = null;
}
if
(con != null) {
con.close();