close
2006 June 05
Java JDBC 連結 MySQL Database (I)
我的學習初步:
1. Download MySQL Database 及 JDBC Driver  (MySQL 叫JDBC connector)
2. 裝好 Database, 然後把jdbc connetor (mysql-connector-java-x.x.xx-bin.jar) 放入JAVA_HOME/jdk1.5.0_06/jre/lib/ext 之中....
3. 完成已上步驟可以開始寫Java 程式碼

import java.sql.*; //用JDBC這個是必須import的
 
public class ConnectToDB {
  public static void main(String args[]){
    //處理console命令
    if(agrs.length != 2){
       System.out.println("Syntax: java ConnectToDB <uid> <password>");
       return;
    }
    try { //載入驅動
      //Register the JDBC driver for MySQL.
      Class.forName("com.mysql.jdbc.Driver");
    }catch( Exception e ) { //載入出錯
      e.printStackTrace();
    }//end catch
   
    try{

 

      //Define URL of database server for
      // database named mysql on the localhost
      // with the default port number 3306.
      String url = "jdbc:mysql://localhost:3306/mysql";
      //Get a connection to the database for a
      // user named root with a blank password.
      // This user is the default administrator
      // having full privileges to do anything.
      Connection con = DriverManager.getConnection(url, args[0], args[1]);
        /**************************************************
        *
        *                  在這裡加入運行程式碼
        *
        ***************************************************/
 

    }catch(SQLException e){

       e.printStackTrace();

    }finally{

       if(con != null){
         try{
            con.close();
         }catch(SQLException e){
            e.printStackTrace();
         }
    }//end finally
  }//end main
}//end class Jdbc11
 
修改Database
先用Connection.createStatement( ) 取得一句Statement
Statement s = con.createStatement();
int updateCounter = s.executeUpdat("INSERT INTO test (col1, col2) + "VALUES(" + var1_value + var2_value +")");

int executeUpdate(String sql) throws SQLException
回傳 no. of update row... 而executeUpdate是用於當SQL Statement不會有任
何回傳如UPDATE, INSERT, DELETE. 有回傳的SQL要用到executeQuery方法, 它會
回傳一個ResultSet用來封裝update value.
 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 oraclebox 的頭像
    oraclebox

    油爆豆腐的空間

    oraclebox 發表在 痞客邦 留言(0) 人氣()