MySQL - Connector J
About MySQL Connector J
MySQLが配布しているjdbcライブラリ jdbc for MySQL Server 例: mysql-connector-java-8.0.27.jar
Jdbc Basics file:JdbcTestConsole.java
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; class JdbcTestConsole { private static final String DRV_NAME = "com.mysql.cj.jdbc.Driver"; private static final String DB_NAME = "java_env"; private static final String URL = "jdbc:MySQL://localhost/" + DB_NAME; public static void main(String[] args) { String USER = "hogefuga"; String PAAA = "fugahoge"; PreparedStatement ps = null; ResultSet rs = null; try { System.out.println("Jdbc Test Console"); Class.forName(DRV_NAME); Connection con = DriverManager.getConnection(URL, USER, PAAA); if (con != null) { System.out.println("Connection is OK"); StringBuilder bldr = new StringBuilder(); bldr.append("SELECT *"); bldr.append("FROM test_data"); ps = con.prepareStatement(bldr.toString()); rs = ps.executeQuery(); while (rs.next()) { System.out.println("id: " + rs.getInt("id") + " title: " + rs.getString("title") + " lastupdate: " + rs.getTimestamp("lastupdate") + " status: " + rs.getInt("status") ); } rs.close(); ps.close(); con.close(); } } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); } } }
コンパイルと実行
javac -cp . JdbcTestConsole.java java -cp .;mysql-connector-java-8.0.27.jar JdbcTestConsole Jdbc Test Console Connection is OK id: 1 title: title01 lastupdate: 2021/??/?? 00:00:00.0 status: 0 id: 2 title: title02 lastupdate: 2021/??/?? 00:00:00.0 status: 0