簡單概述:
PreparedStatement繼承自Statement,但比Statement功能強大的多。
優(yōu)點:
1、PreparedStatement是預(yù)編譯的,比Statement速度快。
當(dāng)同時要執(zhí)行多條相同結(jié)構(gòu)sql語句時使用,這時可以用setObject(),addBatch()和executeBatch()這幾個函數(shù)。
2、可以防止sql注入。
對JDBC而言,SQL注入攻擊只對Statement有效,對PreparedStatement是無效的,這是因為PreparedStatement不允許在插入時改變查詢的邏輯結(jié)構(gòu).
舉例分析:
例一:說明PreparedStatement速度快插入兩條語句只需編譯一次,而Statement則需要編譯兩次。
package com;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class TestPreparedStatement {
publicstatic 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();
con = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
例二:說明PreparedStatement可以防止sql注入。
System.out.println("請輸入用戶名:");
name = input.nextLine();
System.out.println("請輸入密碼:");
pwd = input.nextLine();
String sql = "select * from myuser whereuserName = '" + name + "' and pwd = '" + pwd + "'";
Statementst =con.createStatement();
ResultSet rs = st.executeQuery(sql);
if (rs.next()) {
System.out.println("登陸成功!");
} else {
System.out.println("登陸失敗!");
}
當(dāng)輸入用戶名為任意,密碼為:123' or '1' = '1時,則都可以登錄成功。
System.out.println("請輸入用戶名:");
name = input.nextLine();
System.out.println("請輸入密碼:");
pwd = input.nextLine(【】);
String sql = "select * from myuser whereuserName = ? and pwd = ? ";
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1, name);
pst.setString(2, pwd);
ResultSet rs = pst.executeQuery();
System.out.println(sql);
if (rs.next()) {
System.out.println("登陸成功!");
} else {
System.out.println("登陸失??!");
}
當(dāng)輸入用戶名為任意,密碼為:123' or '1' ='1時,則都可以登錄失敗。防止了sql注入。
愛華網(wǎng)

