liangoogle

          liangoogle
          隨筆 - 9, 文章 - 0, 評論 - 3, 引用 - 0
          數據加載中……

          java代碼實現連接mysql數據庫

          注意修改下面數據庫的名稱、登陸的賬號密碼。
          我用的數據庫名是:test
          賬號密碼都是:root
          =================================
          import java.sql.*;
          public class JDBCTest {
          public static void main(String[] args) {
          // 1. 注冊驅動
          try {
          Class.forName("com.mysql.jdbc.Driver");
          } catch(ClassNotFoundException ex) {
          ex.printStackTrace();
          }
          // 聲明變量,使用,而后關閉
          Connection conn = null;        //數據庫連接
          Statement stmt = null;         //數據庫表達式
          ResultSet rs = null;             //結果集
          try {
          //2. 獲取數據庫的連接
          conn = DriverManager.getConnection
          ("jdbc:mysql://localhost:3306/test","root","root");
          //3. 獲取表達式
          stmt = conn.createStatement();
          //4. 執行SQL
          String sql = "select time from shijian where id=123";
          rs = stmt.executeQuery(sql);
          //5. 現實結果集里面的數據
          while(rs.next()) {
          System.out.println("id為123的time值=" + rs.getString(1));
          }
          }
          catch (Exception ex) {
          ex.printStackTrace();
          }
          finally {
          try {
          if(rs != null) {
          rs.close();
          }
          if(stmt!= null) {
          stmt.close();
          }
          if(conn != null) {
          conn.close();
          }
          } catch(Exception ex) {
          ex.printStackTrace();
          }
          }
          }
          }

          posted on 2011-04-26 00:38 haojinlian 閱讀(138) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 漳州市| 桃江县| 济阳县| 汽车| 大冶市| 灌云县| 当雄县| 汾阳市| 栖霞市| 罗平县| 咸阳市| 葵青区| 阳城县| 巴彦县| 舒兰市| 大石桥市| 天门市| 衡阳县| 合江县| 新乡市| 淮北市| 化隆| 金川县| 洛阳市| 屏东市| 乐至县| 宜阳县| 于田县| 团风县| 长海县| 合山市| 泗阳县| 龙州县| 卢龙县| 昌邑市| 德钦县| 隆化县| 镇江市| 沅江市| 元阳县| 崇信县|