预处理语句

来源:互联网 发布:菠萝饭官方软件 编辑:程序博客网 时间:2024/04/30 22:27

7.2.2  预处理语句

从JDBC API可以看到,PreparedStatement扩展自Statement,PreparedStatement是用于执行预编译的SQL语句,在提高性能方面有很多优点。下面以PreparedStatement举个例子,保存为TestPrepStmt.java。

例7-5  PreparedStatement预处理语句。

  1. import java.sql.*;  
  2. public class TestPrepStmt  
  3. {  
  4.     public static void main(String[] args)  
  5.     {  
  6.         if(args.length!=3)  
  7.         {  
  8.             System.out.println("参数错误!,请重新输入!");  
  9.             System.exit(-1);  
  10.         }  
  11.         int id=0;  
  12.         try  
  13.         {  
  14.            id=Integer.parseInt(args[0]);  
  15.         }  
  16.         catch(NumberFormatException e)  
  17.         {  
  18.             System.out.print("请输入整数");  
  19.             System.exit(-1);  
  20.         }  
  21.         String name=args[1];  
  22.         int age=0;  
  23.         try  
  24.         {  
  25.            age=Integer.parseInt(args[2]);  
  26.         }  
  27.         catch(NumberFormatException e)  
  28.         {  
  29.             System.out.print("请输入整数");  
  30.             System.exit(-1);  
  31.         }  
  32.         PreparedStatement pstmt=null;  
  33.         Connection conn=null;  
  34.         try  
  35.         {  
  36.             Class.forName("com.mysql.jdbc.Driver");  
  37.             String url="jdbc:mysql://127.0.0.1:3306/mysql";  
  38.             String  user="root";  
  39.             String password="admin";  
  40.             conn=DriverManager.getConnection(url,userpassword);  
  41.             pstmt=conn.prepareStatement("insert into dbtest values(?,?,?)");  
  42.             pstmt.setInt(1, id);  
  43.             pstmt.setString(2,name);  
  44.             pstmt.setInt(3,age);  
  45.             pstmt.executeUpdate();  
  46.               
  47.         }  
  48.          catch(ClassNotFoundException e)  
  49.           {  
  50.               e.printStackTrace();  
  51.           }  
  52.           catch(SQLException e)  
  53.           {  
  54.               e.printStackTrace();  
  55.           }  
  56.           finally  
  57.           {  
  58.               try  
  59.               {  
  60.                   if(pstmt!=null)  
  61.                   {  
  62.                       pstmt.close();  
  63.                   }  
  64.                   if(conn!=null)  
  65.                   {  
  66.                       conn.close();  
  67.                   }  
  68.            }  
  69.               catch(SQLException e)  
  70.               {  
  71.                   e.printStackTrace();  
  72.               }  
  73.         }  
  74.     }  

这个程序在运行时,输入参数示例如下:

  1. java  TestPrepStmt  6   wpm  25 
0 0
原创粉丝点击