使用JDBC鏈接MySQL數據庫

Java數據庫鏈接(Java DataBase connectivity簡稱JDBC)
Windows系統下載.zip文件包,Linux平臺下載tar.gz文件包
解壓後找gcfjmysql-connector-java-[version]-bin.jar包,JDBC經過這個文件才能夠正確的鏈接數據庫。
 
打開Eclipse—— 右擊項目——Build Path——Add External JARs 瀏覽剛纔下載的jar包。
 
Apply and Close 後,在項目目錄中能夠找剛纔添加的jar包
 

 

接下來咱們新建DBHelper簡單的數據訪問類,代碼以下:
package com.llt.demo;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
 
public class DBHelper {
       public static final String url = "jdbc:mysql://127.0.0.1/test";
       // jdbc:mysql://host:port/database name
       public static final String name = "com.mysql.jdbc.Driver";
       public static final String user = "root";
       // 數據庫登陸用戶
       public static final String password = "123456";
 
       public Connection connection = null;
       public PreparedStatement pst = null;
 
       // 數據庫登陸密碼
       public DBHelper(String sql) {
             try {
                    Class.forName(name);// 指定鏈接類型
                    connection = DriverManager.getConnection(url, user, password);// 建立鏈接
                    pst = connection.prepareStatement(sql);// 執行Sql語句
 
             } catch (Exception e) {
                    e.printStackTrace();
             }
       }
 
       public void close() {
             try {
                    this.connection.close();
                    this.pst.close();
             } catch (Exception e) {
 
             }
       }
}
 
View Code

 

而後建立一個簡單的類,測試鏈接一下MySQL數據庫
package com.llt.demo;
 
import java.sql.ResultSet;
 
public class test {
 
       public static String sql = "";
       public static DBHelper db = null;
       public static ResultSet ret = null;
 
       public static void main(String[] args) {
             // TODO Auto-generated method stub
             String sql = "select * from book";
             db = new DBHelper(sql);
             try {
                    ret = db.pst.executeQuery();
                    while (ret.next()) {
                           int id = ret.getInt(1);
                           String name = ret.getString(2);
                           System.out.println("id:" + id + ",name:" + name);
 
                    }
                    // 使用完後將數據庫鏈接關閉
                    ret.close();
                    db.close();
             } catch (Exception e) {
                    e.printStackTrace();
             }
       }
}
View Code

 

輸出MySQL數據庫book表中的內容:

 

相關文章
相關標籤/搜索