java中JDBC當(dāng)中PreparedStatement和Statement的效率比較
PreparedStatement和Statement的效率比較
馬克-to-win:前面介紹的Statement接口提供了執(zhí)行sql語句和獲取結(jié)果的基本方法。注意對(duì)于有種情況,即,需要反復(fù)執(zhí)行相同的sql語句時(shí),Sun公司就為我們提供了另外一種對(duì)象:PreparedStatement。它翻譯過來就是: “準(zhǔn)備好的Statement”。用它的好處就是:當(dāng)數(shù)據(jù)庫見到PreparedStatement的sql語句時(shí),數(shù)據(jù)庫端直接先到數(shù)據(jù)庫緩沖區(qū)當(dāng)中找它,如找不到,則會(huì)編譯它一次(就像把java文件編譯成class文件似的,請(qǐng)問java文件能直接運(yùn)行嗎?所以你的“UPDATE login SET name = ? WHERE id = ?”也需要編譯一下,才能執(zhí)行)。如能找到,就直接用。下次再遇到,就省事了。而對(duì)于Statement對(duì)象,就沒有這種待遇。次次見,次次編譯。
馬克- to-win:馬克 java社區(qū):防盜版實(shí)名手機(jī)尾號(hào): 73203。
注意:如果sql語句只執(zhí)行一次,以后不再復(fù)用,則建議采用Statement,因?yàn)镾tatement不會(huì)對(duì)sql進(jìn)行預(yù)編譯。
例:2.2.1
import java.io.IOException;
public class TestMark_to_win {
public static void main(String[] args) throws java.sql.SQLException,
ClassNotFoundException, IOException {
int i = 0;
java.sql.Connection connection = null;
java.sql.PreparedStatement pstmt;
Class.forName("com.mysql.jdbc.Driver");
connection = java.sql.DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "1234");
pstmt = connection
.prepareStatement("UPDATE login SET name = ? WHERE id = ?");
long t = System.currentTimeMillis();
for(i=0;i<10000;i++) {
pstmt.setString(1, "qqqq");
pstmt.setString(2, "2");
pstmt.executeUpdate();
}
t = System.currentTimeMillis() - t;
System.out.println("用了如下時(shí)間:" + t);
pstmt.close();
System.out.println("ok");
connection.close();
}
}
輸出結(jié)果:
用了如下時(shí)間:4256
ok
import java.io.IOException;
public class TestMark_to_win {
public static void main(String[] args) throws java.sql.SQLException,
ClassNotFoundException, IOException {
int i = 0;
java.sql.Connection connection = null;
java.sql.Statement statement;
Class.forName("com.mysql.jdbc.Driver");
connection = java.sql.DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "1234");
statement = connection.createStatement();
String sqlStringupdate = "UPDATE login SET name = 'qqqq'"+" WHERE id = '2'";
long t = System.currentTimeMillis();
for(i=0;i<10000;i++) {
statement.executeUpdate(sqlStringupdate);
}
t = System.currentTimeMillis() - t;
System.out.println("用了如下時(shí)間:" + t);
statement.close();
System.out.println("ok");
connection.close();
}
}
輸出結(jié)果:
用了如下時(shí)間:6578
ok