LoginSignup
20
14

More than 3 years have passed since last update.

MariaDB Connector/J で MariaDB 10.4 に接続する

Last updated at Posted at 2017-07-31

自分用の備忘録として、Windows 10 上で MariaDB Connector/J (JDBC) 2.5.2 経由で MariaDB 10.4 に接続する手順を以下に記します。

Java 8 のインストール

Java SE Development Kit 8 Downloads から jdk-8u221-windows-x64.exe をダウンロード、インストール

Eclipseのインストール

eclipse公式 から eclipse-inst-win64.exe をダウンロード、インストール

MariaDB Connector/J

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

Eclipse : project作成

ここでは test というプロジェクトを作成しました。
newProject.png

newJavaProject.png

Eclipse : class作成

new java class.png

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

addJar.png

image.png

サンプルコードのコンパイル/実行


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

public class test_jdbc {
    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", "root", "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!");
    }
}

実行結果が以下のようになれば問題ありません。

Connector/J 2.5.2

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

Goodbye!
20
14
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
20
14