LoginSignup
1
1

More than 3 years have passed since last update.

MariaDB Connector/J で MariaDB 10.4 に接続(IntelliJ IDEA版)

Last updated at Posted at 2020-03-20

Windows 10 上で MariaDB Connector/J (JDBC) 2.6.0 を用いて MariaDB Server 10.4 に接続する手順を以下に記します。

Java 8 のインストール

Windows版64ビットJava から jdk-8u221-windows-x64.exe をダウンロード,インストール

MariaDB Connector/J

MariaDB Connector/J からmariadb-java-client-2.6.0.jar をダウンロード、C:\Program Files\Java\jdk1.8.0_241\lib にコピーします。

IntelliJ IDEA : project作成

ここでは jdbc_test というプロジェクトを作成しました。

image.png

image.png

IntelliJ IDEA : class作成

src/main/java を右クリックし,New - Java Class で jdbc_test.java を作成します。

image.png

サンプルコード

以下のコードを jdbc_test.java にコピーします。

jdbc_test.java
import java.sql.*;
import org.mariadb.jdbc.internal.util.constant.Version;

public class jdbc_test {
    public static void main(String[] args) {

        Connection conn = null;
        Statement stmt = null;
        try {
            Class.forName("org.mariadb.jdbc.Driver");
            System.out.println("Connector/J " + Version.version + "\n");
            System.out.print("Connecting to DB...");
            conn = DriverManager.getConnection(
                "jdbc:mariadb://192.168.2.104/mysql", "remote", "password");
            System.out.println(" done.");

            stmt = conn.createStatement();
            String sql = "SELECT user,host FROM mysql.user";
            ResultSet hrs = stmt.executeQuery(sql);

            while (hrs.next()) {
                String user = hrs.getString(1);
                String host = hrs.getString(2);
                System.out.println("User: " + user + "@'" + host + "'");
            }
        } catch (SQLException se) {
            //Handle errors for JDBC
            se.printStackTrace();
        } catch (Exception e) {
            //Handle errors for Class.forName
            e.printStackTrace();
        } finally {
            //finally block used to close resources
            try {
                if (stmt != null) { conn.close(); }
            } catch (SQLException se) {} // do nothing
            try {
                if (conn != null) { conn.close(); }
            } catch (SQLException se) {
                se.printStackTrace();
            } //end finally try
        } //end try
        System.out.println("\nGoodbye!");
    }
}

mariadb-java-client-2.6.0.jar を external archive として追加

build.gradle の dependencies に implementation("org.mariadb.jdbc:mariadb-java-client:2.6.0") を追加します。

build.gradle
dependencies {
    implementation("org.mariadb.jdbc:mariadb-java-client:2.6.0")
}

サンプルコードのビルド/実行

Run - RUn 'jdbc_tes' からビルド,実行を行います。
実行結果が以下のようになれば問題ありません。

Connector/J 2.6.0

Connecting to DB... done.
User: remote@'%'
User: mysql@'localhost'
User: root@'localhost'

Goodbye!
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1