Java – MySQL on Ubuntu に接続し、データ検索する方法 No.80

自己投資としてチャレンジしている内容を Blog で公開しています。

今回はオープンソースのリレーショナルデータベースである MySQL に Java で接続し、Select 文を実行する方法について紹介します。(In English Java – Connect to MySQL on Ubuntu and run select query No.80)

▼1. MySQL の概要

MySQL は、Open Source の SQL Database Management System です。現在多くの Cloud 製品上で MySQL のデータベースが利用可能です。Oracle, AWS, Azure などがあります。https://dev.mysql.com/doc/refman/8.0/en/what-is-mysql.html


▼2. 事前準備

2-1. JDK のインストール

zulu の Java 8 openjdk x64 をインストールします。

mkdir  -p /usr/lib/jvm/
cd /usr/lib/jvm/
sudo wget https://cdn.azul.com/zulu/bin/zulu8.66.0.15-ca-jdk8.0.352-linux_x64.tar.gz
sudo tar -xzvf zulu8.66.0.15-ca-jdk8.0.352-linux_x64.tar.gz
sudo mv zulu8.66.0.15-ca-jdk8.0.352-linux_x64 java-8-openjdk-linux_x64

環境変数を設定します。

Vi などのエディター (vi ~/.bashrc) で ~/.bashrc の末尾に以下を記載します。

export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-x64/

JAVA_HOME の環境変数がが正しく設定されたか確認します。

echo $JAVA_HOME

2-2. Visual Studio Code のインストール

https://code.visualstudio.com/docs/setup/linux

sudo snap install --classic code

2-3. Maven のインストール

Apache Kafka Word Count 実装 – Java No.44 “2-3. Apache Maven のインストール” を参照

2-4. 最新の mysql をインストール

# mysql をインストール
sudo apt-get update
sudo apt-get install mysql-server

# mysql service を起動
sudo systemctl start mysql

# マシン Reboot 後、Database server が起動するように設定。
sudo systemctl enable mysql

2-5. mysql java connector をダウンロード

mysql server のインストールが完了した後、mysql java connector を以下のコマンドを実行しインストールします。MySQL :: Download Connector/J から OS のバージョンに合わせ mysql-connector-java_8.0.30-1ubuntu20.04_all.deb をダウンロードします。

downloadingsite

“Download” ボタンをクリックすると以下のサイトに変わり、”No thanks, just start my download” をクックします。

Downloadmysqljavaconnector2

2-6. mysql java connector をインストール

sudo apt install ./mysql-connector-java_8.0.30-1ubuntu20.04_all.deb

2-7. testdb データベースと hiveuser を作成します。

サンプル用に testdb データーベースと、hiveuser ユーザーおよび パスワード hivepassword で接続出来るようにします。

# root ユーザーがパスワードで接続出来るように設定を変更します。
# mysql インストール後、パスワードなしの root で接続します。

sudo mysql -u root

# root ユーザーに対しパスワードで接続できるよう plugin を変更します。

mysql> USE mysql;
mysql> UPDATE user SET plugin='caching_sha2_password' WHERE User='root';
mysql> FLUSH PRIVILEGES;
mysql> select user,host,plugin from mysql.user;
mysql> exit;

# mysql を再起動

sudo service mysql restart

# testdb データーベース作成し、testtbl テーブルを作成後、データを登録します。
# mysql に root で接続、パスワードなし(パスワード求められたら Enter  を押します)

mysql -u root -p

# testdb データベースの作成

mysql> CREATE DATABASE testdb;
mysql> USE testdb;
mysql> create table testtbl (c1 int, c2 int);
mysql> insert testtbl values(1,1),(2,2),(3,3);
mysql> select * from testtbl;
+------+------+
| c1   | c2   |
+------+------+
|    1 |    1 |
|    2 |    2 |
|    3 |    3 |
+------+------+
3 rows in set (0.00 sec)

# hiveuser ユーザー作成および パスワード hivepassword で接続出来るようにします。

mysql> CREATE USER 'hiveuser'@'localhost' IDENTIFIED BY 'hivepassword';
mysql> GRANT all on *.* to 'hiveuser'@'localhost';
mysql> flush privileges;
mysql> exit;

▼3. MySQL に接続し、select 文を実行する Java のコード

3-1. Apache Maven によるプロジェクトを作成

mvn archetype:generate -DinteractiveMode=false -DgroupId=org.example.mysqlcon -DartifactId=mysqlconnection -DarchetypeArtiFactId=maven-archetype-quickstart

3-2. デフォルトで作成された App.java および AppTest.java を削除

rm ./mysqlconnection/src/main/java/org/example/mysqlcon/App.java 
rm ./mysqlconnection/src/test/java/org/example/mysqlcon/AppTest.java 

3-3. Visual Studio Code 起動

cd ./mysqlconnection
$code .

3-4. pom.xml に以下を追記し保存 (Ctrl+S)

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.30</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

3-5. MySQL に接続し、select 文を実行

データベースは事前に作成した testdb を利用し、ユーザー hiveuser と、そのパスワードを指定しています。

package org.example.mysqlcon;

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class mysqlcontest {

    private static final Logger log;
    private static final String DB_URL = "jdbc:mysql://localhost:3306/testdb";
    private static final String USER = "hiveuser";
    private static final String PASSWORD = "hivepassword";

    static {
        log = Logger.getLogger(mysqlcontest.class.getName());
    }

    public static void main(String[] args) throws SQLException {
        Connection conn = null;
        Statement stmt = null;

        // Register JDBC driver
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            log.log(Level.SEVERE, "Where is your MySQL JDBC Driver?", e);
            return;
        }

        try {
            // Register JDBC driver
            Class.forName("com.mysql.cj.jdbc.Driver");

            // pen a connection
            log.log(Level.INFO, "Connecting to database...");
            conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);

            // Execute a query
            log.log(Level.INFO, "Creating statement...");
            stmt = conn.createStatement();
            String sql = "SELECT * FROM testtbl";
            ResultSet rs = stmt.executeQuery(sql);

            // Extract data from result set
            while (rs.next()) {
                // Retrieve by column name
                int c1 = rs.getInt("c1");
                int c2 = rs.getInt("c2");

                // Display values
                System.out.println("c1: " + c1 + ", c2: " + c2);
            }

            //Clean-up environment
            rs.close();
        } 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)
                    stmt.close();
            } catch (SQLException se2) {
            } // nothing we can do
            try {
                if (conn != null)
                    conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            } // end finally try
        } // end try
        log.log(Level.INFO, "Operation done successfully");
    }
} 

3-6. 実行結果

Nov 21, 2022 4:48:14 PM org.example.mysqlcon.mysqlcontest main
INFO: Connecting to database...
Nov 21, 2022 4:48:15 PM org.example.mysqlcon.mysqlcontest main
INFO: Creating statement...
c1: 1, c2: 1
c1: 2, c2: 2
c1: 3, c2: 3
Nov 21, 2022 4:48:15 PM org.example.mysqlcon.mysqlcontest main
INFO: Operation done successfully

▼4. 参考情報

  1. MySQL  https://dev.mysql.com/doc/refman/8.0/en/what-is-mysql.html
  2. VS Code https://code.visualstudio.com/docs/setup/linux
  3. Maven Install Apache Kafka Word Count 実装 – Java No.44 “2-3. Apache Maven” 参照
  4. mysql java connector ダウンロード MySQL :: Download Connector/J 

以上です。参考になりましたら幸いです。




コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です