首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫

JDBC 連線 MySQL 實戰:從建庫到 Java 程式碼完整範例

     編輯:MySQL 資料庫相關知識

環境準備

  1. 安裝 MySQL,建立資料庫 studentinfo:
    CREATE DATABASE studentinfo;
  2. 下載 MySQL Connector/J JDBC 驅動(如 mysql-connector-java-5.0.3-bin.jar),加入 CLASSPATH 或放入 Tomcat common/lib、shared/lib。

Java 連線範例

import java.sql.*;

public class ConnectToMySQL {
    public static Connection getConnection() throws SQLException, ClassNotFoundException {
        String url = "jdbc:mysql://localhost:3306/studentinfo";
        Class.forName("com.mysql.jdbc.Driver");
        String user = "root";
        String password = "";
        return DriverManager.getConnection(url, user, password);
    }

    public static void main(String[] args) {
        try (Connection con = getConnection();
             Statement stmt = con.createStatement()) {

            stmt.execute("DROP TABLE IF EXISTS student");
            stmt.execute("CREATE TABLE student (id INT NOT NULL AUTO_INCREMENT, name VARCHAR(20) NOT NULL DEFAULT 'name', math INT NOT NULL DEFAULT 60, PRIMARY KEY(id))");
            stmt.execute("INSERT INTO student VALUES (1,'AAA',99)");
            stmt.execute("INSERT INTO student VALUES (2,'BBB',77)");
            stmt.execute("INSERT INTO student VALUES (3,'CCC',65)");

            ResultSet rs = stmt.executeQuery("SELECT * FROM student");
            System.out.println("學號 姓名 數學成績");
            while (rs.next()) {
                System.out.printf("%d %s %s%n", rs.getInt("id"), rs.getString("name"), rs.getString("math"));
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }
}

執行結果

輸出結果截圖

注意事項

  • 確認 MySQL 服務已啟動(Windows 可用 services.msc 檢查)。
  • 驅動版本需與 MySQL 版本相容,官方下載:https://www.mysql.org。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved