MySQL for Java

      在〈MySQL for Java〉中尚無留言

手動下載驅動

請先到 https://dev.mysql.com/downloads/connector/j/ 下載最新的驅動程式,然後選取 Platform independent。

下載完成後, 解壓縮.

NetBeans 加入 jar Library

在 NetBeans中, 開啟新專案, 然後於NetBeans的專案名稱下的 Libraries 按右鍵 Add JAR/Forder,再選取剛剛解壓縮的.jar檔。

java_mysql

自動下載驅動程式

如果是使用 gradle 的話,請可於 build.gradle 下加入如下藍色部份。

dependencies {
    testImplementation platform('org.junit:junit-bom:5.10.0')
    testImplementation 'org.junit.jupiter:junit-jupiter'
    implementation("mysql:mysql-connector-java:8.0.33")
}

最新的版本可由如下網址查詢 https://repo.maven.apache.org/maven2/mysql/mysql-connector-java/

Java代碼載入驅動程式

先使用 Class.forName 載入驅動程式。

try {
    Class.forName("com.mysql.cj.jdbc.Driver");
} 
catch (ClassNotFoundException ex) {}

請注意, 前後都要用try-catch包含, 抓取 ClassNotFoundException 例外

建立連線

在NetBeans12 中,可能有些bug,無法用 Alt+Enter 自動輸入 java.sql 套件,所以要手動自已打上去。

import java.sql.*;

連線字串有沒有加 useSSL=false 及 serverTimezone=UTC 好像都沒差。

Connection conn=DriverManager.getConnection("jdbc:mysql://localhost/cloud?useSSL=false&serverTimezone=UTC", "帳號","密碼");

如果出現如下的錯誤,才加入 serverTimezone=UTC。

The server time zone value '�x�_�зǮɶ�' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specifc time zone value if you want to utilize time zone support

連線補充說明

在Android中,連線的建立及其他的SQL語法操作,都必需在新的執行緒上執行。如果是在Java上,若操作時間過久,也要考慮使用新的執行緒。

建立命令物件

Statement為命令物件, 執行後, 會產生ResultSet資料集.

資料集的取得, 可以使用 rs.getString(欄位數) or rs.getString(欄位名)
如果是欄位數, 記得是從 1 開始. 如果是欄位名, 需加 “”

Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from 台灣股市");
while (rs.next()) {
    System.out.printf("%s, %s, %s\n", 
    rs.getString(1), 
    rs.getString("護照"), 
    rs.getString(3));
}

完整代碼

底下是完整代碼

package net.ddns.mahaljsp;
import java.sql.*;
public class Main {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn= DriverManager.getConnection(
               "jdbc:mysql://ip/cloud",
               "帳號",
               "密碼"
            );
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("select * from 台灣股市");
            while (rs.next()) {
                System.out.printf("%s, %s, %s\n",
                        rs.getString(2),
                        rs.getFloat("開盤"),
                        rs.getFloat("收盤"));
            }
        }
        catch (ClassNotFoundException ex) {} 
        catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

模擬 Python 用法

上述代碼中,要用 Class.forName 載入驅動,使用 DriverManager.getConnection 建立連線,再使用 conn.createStatement 建立命令物件,實在很煩人,如果能像 Python 那麼直覺就好了。

不過此法是練習物件導向用的,實際上不建議這麼作。

package net.ddns.mahaljsp;
import java.sql.*;
public class Main {
    public static void main(String[] args) {
        try(Connect conn= mysql.connect(
                "ip",
                "帳號",
                "密碼",
                "資料庫"
        )) {
            Cursor cursor=conn.cursor();
            try (ResultSet rs = cursor.executeQuery(
                    "select * from 台灣股市"
            )) {
                while (rs.next()) {
                    System.out.printf("%s, %s, %s\n",
                            rs.getString(2),
                            rs.getFloat("開盤"),
                            rs.getFloat("收盤"));
                }
            }
            catch(SQLException e){
                throw new RuntimeException(e);
            }
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
class Cursor{
    Statement stmt;
    public Cursor(Statement stmt){
        this.stmt=stmt;
    }
    public ResultSet executeQuery(String cmd){
        try {
            return stmt.executeQuery(cmd);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
class Connect implements AutoCloseable {
    Connection conn;
    public Connect(Connection conn){
        this.conn=conn;
    }
    public Cursor cursor(){
        try {
            return new Cursor(conn.createStatement());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void close() throws Exception {
        conn.close();
    }
}
class mysql{
    public static Connect connect(
            String url,
            String userAccount,
            String password,
            String database
    ){
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn= DriverManager.getConnection(
                    String.format("jdbc:mysql://%s/%s", url, database),
                    userAccount,
                    password
            );
            return new Connect(conn);
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *