自己投資としてチャレンジしている内容を Blog で公開しています。今回は MySQL に接続し Select した結果をローカルファイルに出力する Java コードを紹介します。(In English Java -Save the results of select for MySQL into a file No.85)
Summary
▼1. 事前準備
1-1. MySQL の環境を準備し、データを作成しておきます。
Java – MySQL on Ubuntu に接続し、データ検索する方法 No.80
# 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)
▼2. MySQL に接続し、select を実行した結果をローカルファイルに出力する Java コード
2-1. Apache Maven によるプロジェクトを作成
mvn archetype:generate -DinteractiveMode=false -DgroupId=org.example.mysqlcon -DartifactId=mysqlconnection -DarchetypeArtiFactId=maven-archetype-quickstart
2-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
2-3. Visual Studio Code 起動
cd ./mysqlconnection
$code .
2-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> </project>
2-5. MySQL に接続し、select を実行した結果をローカルファイルに保存ます。
以下のような mysqlsavetest.java ファイルを作成します。データベースは事前に作成した testdb を利用し、ユーザー hiveuser と、そのパスワードを指定しています。
package org.example.mysqlcon;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.ArrayList;
import java.util.List;
import java.io.FileWriter;
import java.io.IOException;
public class mysqlsavetest{
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";
private static final String filename = "/home/xxx/mysqlOutput.csv";
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);
List<String> list = new ArrayList<String>();
while (rs.next()) {
String id = rs.getString("c1");
String num = rs.getString("c2");
String str = id + "," + num;
list.add(str);
}
rs.close();
// save list to file
try{
FileWriter fw = new FileWriter(filename);
for(String str : list){
fw.write(str + System.getProperty("line.separator"));
}
fw.close();
} catch(IOException e){
e.printStackTrace();
}
} 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");
}
}
2.6 実行結果
コードを実行し出力されたファイルを確認
$ cat mysqlOutput.csv 1,1 2,2 3,3 |
▼3. 参考情報
- MySQL https://dev.mysql.com/doc/refman/8.0/en/what-is-mysql.html
- Java – MySQL on Ubuntu に接続し、データ検索する方法 No.80
以上です。参考になりましたら幸いです。