prepareStatement和Statement区别

来源:互联网 发布:js json循环遍历 编辑:程序博客网 时间:2024/05/17 23:28

1:创建时的区别:
   Statement stm=con.createStatement();
   PreparedStatement pstm=con.prepareStatement(sql); 
   执行的时候: 
   stm.execute(sql); 
   pstm.execute();


2: pstm一旦绑定了SQL,此pstm就不能执行其他的Sql,即只能执行一条SQL命令。
stm可以执行多条SQL命令。


3: 对于执行同构的sql(只有值不同,其他结构都相同),用pstm的执行效率比较的高,对于异构的SQL语句,Statement的执行效率要高。


4:当需要外部变量的时候,pstm的执行效率更高.

 

Code:
  1. 下面是一个statement的列子 :    
  2.   
  3. package com.JDBC.proc;        
  4.   
  5. public class StatementTest {    
  6.          
  7.     public static void main(String args[]){    
  8.              
  9.         Connection conn=null;    
  10.         Statement stm=null;    
  11.         ResultSet rs=null;    
  12.              
  13.         try {    
  14.             conn=DBTool.getConnection();    
  15.             String sql="select EmpNo,EName from emp " +    
  16.                     "where empNo=7499";    
  17.             stm=conn.createStatement();    
  18.             rs=stm.executeQuery(sql);    
  19.             while(rs.next()){    
  20.                 System.out.println(rs.getInt(1)+"---"+rs.getString(2));    
  21.             }    
  22.         } catch (SQLException e) {    
  23.             e.printStackTrace();    
  24.         } catch (Exception e) {    
  25.   
  26.             e.printStackTrace();    
  27.         }finally{    
  28.             DBTool.release(rs, stm, conn);    
  29.             }    
  30.              
  31.     }    
  32.         
  33. }   

 

 

Code:
  1. 下面是关于prepareStatement的列子:    
  2.   
  3. import java.sql.*;    
  4. public class PrepareStatement {    
  5.          
  6.     public static void main(String[] args){    
  7.              
  8.         Connection conn=null;    
  9.         PreparedStatement psmt=null;    
  10.         ResultSet rs=null;    
  11.              
  12.         try {    
  13.             conn=DBTool.getConnection();    
  14.             String sql="select EmpNo,Ename " +    
  15.                     "from emp " +    
  16.                     "where EmpNo=?";    
  17.             psmt=conn.prepareStatement(sql);    
  18.             psmt.setInt(17499);    
  19.                  
  20.             rs=psmt.executeQuery();    
  21.             while(rs.next()){    
  22.                 System.out.println(rs.getInt(1)+"---"+rs.getString(2));    
  23.                      
  24.             }    
  25.         } catch (SQLException e) {    
  26.             // TODO Auto-generated catch block    
  27.             e.printStackTrace();    
  28.         } catch (Exception e) {    
  29.             e.printStackTrace();    
  30.         }finally{    
  31.             DBTool.release(rs, psmt, conn);    
  32.         }    
  33.              
  34.     }    
  35.   
  36. }  

 

原创粉丝点击