1. package book.database;  
  2.  
  3. import java.sql.Connection;  
  4. import java.sql.PreparedStatement;  
  5. import java.sql.SQLException;  
  6.  
  7. /**  
  8.  * 使用PreparedStatement传递变量  
  9.  */  
  10. public class UsingPreparedStatement {  
  11.  
  12.     public static void main(String[] args) throws ClassNotFoundException,  
  13.             SQLException {  
  14.         String dbName = "studentdb";  
  15.         String userName = "test";  
  16.         String password = "test";  
  17.         // SQL中有多个问号,表示这些地方的值还不确定  
  18.         String sql = "INSERT INTO student_basic (name, age, score) VALUES (?,?,?)";  
  19.         Connection con = null;  
  20.         PreparedStatement psm = null;  
  21.         try {  
  22.             // 获得数据库连接  
  23.             con = DBConnector.getMySQLConnection(null, null, null, dbName,  
  24.                     userName, password);  
  25.             psm = con.prepareStatement(sql);  
  26.               
  27.             // 将SQL语句中的?赋值  
  28.             psm.setString(1, "wangwu");  
  29.             psm.setInt(2, 17);  
  30.             psm.setDouble(3, 98);  
  31.             psm.executeUpdate();  
  32.         } catch (ClassNotFoundException e1) {  
  33.             throw e1;  
  34.         } catch (SQLException e2) {  
  35.             throw e2;  
  36.         } finally {  
  37.             OperateDB.closeStatement(psm);  
  38.             // 关闭数据库连接  
  39.             OperateDB.closeConnection(con);  
  40.         }  
  41.     }  
  42. }