1、創建時的區別:
Statement stm = con.createStatement();
PrepareStatement pstm = con.prepareStatement(sql);
執行的時候:
stm.execute(sql);
pstm.execute();
2、pstm一旦綁定了SQL,此pstm就不能執行其他的SQL,即只能執行一條SQL命令。stm可以執行其他的SQL命令。
3、對於執行同構的SQL(只有值不同,其他結構都相同),用pstm的執行效率比較高,對於異構的SQL語句,Statement的執行效率要高。
4、當需要外部變量的時候,pstm的執行效率更高。
下面是一個statement的例子
package JDBC;
import com.mysql.jdbc.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class StatementTest {
public static void main(String[] args){
Connection connection = null;
Statement statement = null;
ResultSet rSet = null;
try{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/scutcs", "root", "yuping");
String sqlString = "SELECT SNO,SNAME FROM STUDENT WHERE HEIGHT = 0.00";
statement = (Statement) connection.createStatement();
rSet = statement.executeQuery(sqlString);
while(rSet.next()){
System.out.println(rSet.getString(1) + " " +rSet.getString(2));
}
}catch(SQLException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
rSet.close();
statement.close();
connection.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
下面是一個PrepareStatement的例子
package JDBC;
import java.security.interfaces.RSAKey;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
public class PrepareStatementTest {
public static void main(String[] args){
Connection connection = null;
PreparedStatement psmt = null;
ResultSet resultSet = null;
try{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/scutcs", "root", "yuping");
String sqlString = "SELECT SNO, SNAME,SEX FROM STUDENT WHERE SEX = ?";
psmt = (PreparedStatement) connection.prepareStatement(sqlString);
psmt.setString(1, "1");
resultSet = psmt.executeQuery();
while(resultSet.next()){
System.out.println(resultSet.getString(1) + " " + resultSet.getString(2) + " " + resultSet.getString(3));
}
}catch(SQLException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
resultSet.close();
psmt.close();
connection.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
其中 psmt.setString(1,"1");第一個參數代表第一個"?"應該設置的值。