Eclipse連接MySQL數據庫


今年自從開始了AS3開發,感覺離java越來越遠了,竟然連基本的連接數據庫都要查資料了。。。不說了,自己學一篇吧。

在開發之前先開下載安裝mysql吧,安裝方法:http://www.duote.com/tech/1/2430_1.html

安裝好之后,就可以利用myEclipse或者intellij IDEA進行數據庫的開發了。但是在連接數據庫之前首先需要有一個數據庫驅動程序,就是Java的jar包。

可以到這里下載Java的mysql的驅動包:http://download.csdn.net/detail/weierbufan/8396207

1、導入數據庫驅動:

打開Eclipse,創建一個項目(my),

操作:右鍵點擊my--->build Path--->add external Archiver...選擇jdbc驅動,點擊確定。

在項目列表中可以看到:

2、驗證數據庫是不是已經連接可用了。。程序如下:

import java.sql.*;
public class TestJDB {
  public static void main(String args[]) {
    try {
      Class.forName("com.mysql.jdbc.Driver");     //加載MYSQL JDBC驅動程序   
      //Class.forName("org.gjt.mm.mysql.Driver");
     System.out.println("Success loading Mysql Driver!");
    }
    catch (Exception e) {
      System.out.print("Error loading Mysql Driver!");
      e.printStackTrace();
    }
    try {
      Connection connect = DriverManager.getConnection(
          "jdbc:mysql://localhost:3306/tx","root","126");
           //連接URL為   jdbc:mysql//服務器地址/數據庫名  ,后面的2個參數分別是登陸用戶名和密碼

      System.out.println("Success connect Mysql server!");
      Statement stmt = connect.createStatement();
      ResultSet rs = stmt.executeQuery("select * from myclass");
                                                              
while (rs.next()) {
        System.out.println(rs.getInt(1)+"\t"
                +rs.getString(2)+"\t"
                +rs.getInt(3)+"\t"
                +rs.getDouble(4)+"\t"
                +rs.getInt(5));
      }
    }
    catch (Exception e) {
      System.out.print("get data error!");
      e.printStackTrace();
    }
    
  }
}

運行上面的程序會看到如下的結果:

說明數據庫已經連接成功。。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM