1. 程式人生 > >Myeclipse連線資料庫

Myeclipse連線資料庫

1、先將下載好jdbc複製貼上進你的專案

2、右鍵專案  Build Path -> add Libraries->User Library->User Libraries->New -> 命名extendlib->Add JARS

 把上一步複製的jdbc等lib包加進去

3、Build Path ->Configure  Build Path ->Add Library->User Library->extendlib

然後連線基本完成。

4、通過建一個 ConnectJdbc.java 測試是否連線成功

import java.sql.*;

public class ConnectJdbc {
   public static void main(String args[]) {
     try {
       Class.forName("com.mysql.jdbc.Driver");     //載入MYSQL JDBC驅動程式  
      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/weatheraqi","root","1234");
            //連線URL為   jdbc:mysql//伺服器地址/資料庫名  ,後面的2個引數分別是登陸使用者名稱和密碼

       System.out.println("Success connect Mysql server!");
       Statement stmt = connect.createStatement();
       ResultSet rs = stmt.executeQuery("select * from bar");
                                                               //bar 為你表的名稱
 while (rs.next()) {
         System.out.println(rs.getString("name"));
       }
     }
     catch (Exception e) {
       System.out.print("get data error!");
       e.printStackTrace();
     }
   }
 }