2
2

More than 3 years have passed since last update.

JavaプロジェクトでMySQLに接続してみる

Posted at

参考にしたサイト

環境

Eclipse2020-12
java8

javaプロジェクトの作成

image.png

MySQLのドライバーをダウンロード

image.png

右下のダウンロード
image.png
からZIPをダウンロードするとmysql-connector-java-8.0.22.jarがあります。これをワークスペースなどにコピーしてjavaプロジェクトの参照ライブラリに追加します。

image.png

参照ライブラリに追加

image.png

プロジェクトにカーソルを合わせて
ビルド・パス→外部アーカイブの追加
から先程ダウンロードしたmysql-connector-java-8.0.22.jarを追加します

image.png

接続を実行するクラス

Main.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Main{
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/testdb?serverTimezone=UTC";
        String user = "makoto";
        String password = "makoto";

        try {
            Connection conn = DriverManager.getConnection(url, user, password);
            String sql = "SELECT * FROM employees";
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while(rs.next()) {
                Integer code        = rs.getInt(1);
                String name         = rs.getString(2);
                Integer age         = rs.getInt(3);
                String section  = rs.getString(4);
                System.out.println(
                        "code: " + code + "\n" +
                        "name: " + name + "\n" +
                        "age: " + age + "\n" +
                        "section: " + section
                        );
                rs.close();
                ps.close();
                conn.close();
                System.exit(0);

            }
        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}

DriverManager.getConnection(url, user, password)で接続に必要なURLとユーザー名とパスワードを渡します。

テーブル

image.png

image.png

こんな感じのテーブルを用意しときました。
SQLはSELECT * FROM employeesとして全レコードを取得します。

ResultSetで要素番号についての注意点

大体最初の配列などは、0から始まるけど、ResultSetの場合は1から始まる。

つまり

// 0から始めるとエラー
rs.getInt(0);

// 1から始める
rs.getInt(1);

0から始めた場合、次のようなエラーが表示される。

Column Index out of range, 0 < 1.

jdbc:mysql://localhost:3306/testdb?serverTimezone=UTC"としないとエラーになる

// 最後の?serverTimezone=UTCを書いておかないとエラーになります
String url = "jdbc:mysql://localhost:3306/testdb?serverTimezone=UTC";

表示されるエラーメッセージ

java.sql.SQLException: The server time zone value '���� (�W����)' 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 specific time zone value if you want to utilize time zone support.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:76)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:198)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
    at Main.main(Main.java:13)
Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException: The server time zone value '���� (�W����)' 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 specific time zone value if you want to utilize time zone support.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:85)
    at com.mysql.cj.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:134)
    at com.mysql.cj.protocol.a.NativeProtocol.configureTimezone(NativeProtocol.java:2186)
    at com.mysql.cj.protocol.a.NativeProtocol.initServerSession(NativeProtocol.java:2209)
    at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:1318)
    at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:967)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:826)
    ... 6 more

何故か文字化けしてます。。。Eclipseで実行したもので、コンソールに表示されたまんま載せました。コンソール上も文字化けしていました。

Timezoneなどの設定は、SpringBootなどではapplication.propertiesに記載するものだと思われます。不確か(´・ω・`)

2
2
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
2
2