7.2.2 预处理语句
从JDBC API可以看到,PreparedStatement扩展自Statement,PreparedStatement是用于执行预编译的SQL语句,在提高性能方面有很多优点。下面以PreparedStatement举个例子,保存为TestPrepStmt.java。
例7-5 PreparedStatement预处理语句。
- import java.sql.*;
- public class TestPrepStmt
- {
- public static void main(String[] args)
- {
- if(args.length!=3)
- {
- System.out.println("参数错误!,请重新输入!");
- System.exit(-1);
- }
- int id=0;
- try
- {
- id=Integer.parseInt(args[0]);
- }
- catch(NumberFormatException e)
- {
- System.out.print("请输入整数");
- System.exit(-1);
- }
- String name=args[1];
- int age=0;
- try
- {
- age=Integer.parseInt(args[2]);
- }
- catch(NumberFormatException e)
- {
- System.out.print("请输入整数");
- System.exit(-1);
- }
- PreparedStatement pstmt=null;
- Connection conn=null;
- try
- {
- Class.forName("com.mysql.jdbc.Driver");
- String url="jdbc:mysql://127.0.0.1:3306/mysql";
- String user="root";
- String password="admin";
- conn=DriverManager.getConnection(url,user,password);
- pstmt=conn.prepareStatement("insert into dbtest values(?,?,?)");
- pstmt.setInt(1, id);
- pstmt.setString(2,name);
- pstmt.setInt(3,age);
- pstmt.executeUpdate();
- }
- catch(ClassNotFoundException e)
- {
- e.printStackTrace();
- }
- catch(SQLException e)
- {
- e.printStackTrace();
- }
- finally
- {
- try
- {
- if(pstmt!=null)
- {
- pstmt.close();
- }
- if(conn!=null)
- {
- conn.close();
- }
- }
- catch(SQLException e)
- {
- e.printStackTrace();
- }
- }
- }
- }
这个程序在运行时,输入参数示例如下:
- java TestPrepStmt 6 wpm 25