JDBC code

banq發表於2004-05-10

1. 
Class.forName("sun.jdbc.odbc.xxxxx");
Class.ForName("com.mysql.jdbc.Driver");

Driver.class --> mysql.jar

2. use JDBC
(1) create connection--> connection pool --> thread Pool
   Connection conn = DriverManager.getConnection("?????????");
   Connection conn = getDataSource();

   jdbc:mysql://[hostname]:[port]/dbname?[]
   jdbc:mysql://192.168.0.2/mydb?user=banq&password=999

(2) send SQL 
   Statement stmt = conn.createStatement();
   stmt.execute("select * from user");

   PreparedStatement prestmt = conn.prepareStatement("select userId, password, sex, grade 
                                                from user where userId=? and password=?")
   prestmt.setString(1, "banq");
   prestmt.setString(2, "999");   


   //get the restult of query: ResultSet 
   try{

      ResultSet result = prestmt.executeQuery();
      String userId;
      String sex;
      while(result.next()){
         userId = result.getString(1);
         sex = result.getString(3);
         ......
      }
      system.println("found sex is " + sex); //log4j 
     //log.debug(" found sex is " + sex);
   }catch(Exception ex){
      system.println(" sql error " + ex);
   }
  



(3) close connection
   prestmt.close();
   result.close();
   conn.close();


<p class="indent">