liangoogle

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

          java代碼實現(xiàn)連接mysql數(shù)據(jù)庫

          注意修改下面數(shù)據(jù)庫的名稱、登陸的賬號密碼。
          我用的數(shù)據(jù)庫名是: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;        //數(shù)據(jù)庫連接
          Statement stmt = null;         //數(shù)據(jù)庫表達式
          ResultSet rs = null;             //結果集
          try {
          //2. 獲取數(shù)據(jù)庫的連接
          conn = DriverManager.getConnection
          ("jdbc:mysql://localhost:3306/test","root","root");
          //3. 獲取表達式
          stmt = conn.createStatement();
          //4. 執(zhí)行SQL
          String sql = "select time from shijian where id=123";
          rs = stmt.executeQuery(sql);
          //5. 現(xiàn)實結果集里面的數(shù)據(jù)
          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)  編輯  收藏


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


          網(wǎng)站導航:
           
          主站蜘蛛池模板: 民权县| 武邑县| 涟水县| 花莲县| 银川市| 木兰县| 兴安盟| 吴川市| 大埔区| 买车| 托克逊县| 阳城县| 平陆县| 根河市| 菏泽市| 涟源市| 安陆市| 镇江市| 莎车县| 安康市| 西华县| 库伦旗| 高陵县| 那坡县| 大宁县| 青阳县| 多伦县| 张家界市| 三江| 宜宾县| 孟村| 颍上县| 碌曲县| 绥芬河市| 灌南县| 蓬安县| 城口县| 宁南县| 民勤县| 永寿县| 德昌县|