prepareStatement與Statement的區(qū)別
1:創(chuàng)建時(shí)的區(qū)別:
Statement stm=con.createStatement();
PreparedStatement pstm=con.prepareStatement(sql);
執(zhí)行的時(shí)候:
stm.execute(sql);
pstm.execute();
2: pstm一旦綁定了SQL,此pstm就不能執(zhí)行其他的Sql,即只能執(zhí)行一條SQL命令。
stm可以執(zhí)行多條SQL命令。
3: 對(duì)于執(zhí)行同構(gòu)的sql(只有值不同,其他結(jié)構(gòu)都相同),用pstm的執(zhí)行效率比較的高,對(duì)于異構(gòu)的SQL語(yǔ)句,Statement的執(zhí)行效率要高。
4:當(dāng)需要外部變量的時(shí)候,pstm的執(zhí)行效率更高.
下面是一個(gè)statement的列子 :
Java代碼
package com.JDBC.proc;
import java.sql.*;
public class StatementTest {
public static void main(String args[]){
Connection conn=null;
Statement stm=null;
ResultSet rs=null;
try {
conn=DBTool.getConnection();
String sql="select EmpNo,EName from emp where empNo=7499";
stm=conn.createStatement();
rs=stm.executeQuery(sql);
while(rs.next()){
System.out.println(rs.getInt(1)+"---"+rs.getString(2));
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally{
DBTool.release(rs, stm, conn);
}
}
}
他的主要作用闡述Statement的用法。
下面是關(guān)于prepareStatement的列子:
Java代碼
package com.JDBC.proc;
import java.sql.*;
public class PrepareStatement {
public static void main(String[] args){
Connection conn=null;
PreparedStatement psmt=null;
ResultSet rs=null;
try {
conn=DBTool.getConnection();
String sql="select EmpNo,Ename from emp where EmpNo=?";
psmt=conn.prepareStatement(sql);
psmt.setInt(1, 7499);
rs=psmt.executeQuery();
while(rs.next()){
System.out.println(rs.getInt(1)+"---"+rs.getString(2));
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally{
DBTool.release(rs, psmt, conn);
}
}
}
聯(lián)系客服