`

prepareStatement与Statement的区别

    博客分类:
  • JDBC
 
阅读更多
PrepareStatement与Statement的主要区别:
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的执行效率更高.
Statement example:

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);
   }
  
 }
 
}

PrepareStatement example:

   
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) {   
               // TODO Auto-generated catch block   
               e.printStackTrace();   
           } catch (Exception e) {   
               e.printStackTrace();   
           }finally{   
              DBTool.release(rs, psmt, conn);   
           }   
              
       }   
     
   }  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics