JDBC之Java連接MySQL數(shù)據(jù)庫(kù)

Java連接MySQL數(shù)據(jù)庫(kù)需要一個(gè)jar包mysql-connector-java-5.1.39-bin.jar, 我們創(chuàng)建一個(gè)Java Project,并且將這個(gè)包導(dǎo)入進(jìn)去

1.創(chuàng)建測(cè)試數(shù)據(jù)

我是用SQLyog創(chuàng)建的數(shù)據(jù)庫(kù),這里貼出創(chuàng)建代碼

CREATE DATABASE sample_db;

CREATE TABLE student(
    _id int(10),
    name varchart(20)
) CHARTSET=utf-8

INSERT INTO student(_id,name) VALUES(100,'張三');
INSERT INTO student(_id,name) VALUES(101,'李四');

2.創(chuàng)建MySQLConnectionDemo.java

package demo;

import java.sql.*;

public class MySQLConnectionDemo {
    // JDBC 驅(qū)動(dòng)名及數(shù)據(jù)庫(kù) URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
    static final String DB_URL = "jdbc:mysql://localhost:3306/samp_db";
 
    // 數(shù)據(jù)庫(kù)的用戶(hù)名與密碼,需要根據(jù)自己的設(shè)置
    static final String USER = "root";
    static final String PASS = "123";
 
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try{
            // 注冊(cè) JDBC 驅(qū)動(dòng)
            Class.forName("com.mysql.jdbc.Driver");
        
            // 打開(kāi)鏈接
            System.out.println("正在連接數(shù)據(jù)庫(kù)...");
            conn = DriverManager.getConnection(DB_URL,USER,PASS);
        
            // 執(zhí)行查詢(xún)
            System.out.println(" 實(shí)例化Statement");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT * FROM student";
            ResultSet rs = stmt.executeQuery(sql);
        
            // 展開(kāi)結(jié)果集數(shù)據(jù)庫(kù)
            while(rs.next()){
                // 通過(guò)字段檢索
                int id  = rs.getInt("_id");
                String name = rs.getString("name");
    
                // 輸出數(shù)據(jù)
                System.out.print("學(xué)號(hào): " + id);
                System.out.print(", 姓名: " + name+"\n");
            }
            // 完成后關(guān)閉
            rs.close();
            stmt.close();
            conn.close();
        }catch(SQLException se){
            // 處理 JDBC 錯(cuò)誤
            se.printStackTrace();
        }catch(Exception e){
            // 處理 Class.forName 錯(cuò)誤
            e.printStackTrace();
        }finally{
            // 關(guān)閉資源
            try{
                if(stmt!=null) stmt.close();
            }catch(SQLException se2){
            }// 什么都不做
            try{
                if(conn!=null) conn.close();
            }catch(SQLException se){
                se.printStackTrace();
            }
        }
        System.out.println("斷開(kāi)數(shù)據(jù)庫(kù)");
    }
}

輸出.PNG
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容