DB接続のサンプル - funakosi/programming GitHub Wiki

  • 殴り書き
package com.example.selenide;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class DBConnection {

	String URL;
	String USER;
	String PASS;
	Connection conn;

	@Before
	public void setUp() {
		URL = "jdbc:mysql://192.168.33.10:3306/mydb01";
		USER = "funa";
		PASS = "funa";
	}

	@After
	public void tearDown() {

	}

	@Test
	public void basicConnect() {
		try {
			//https://mvnrepository.com/artifact/commons-dbutils/commons-dbutils/1.7
			conn = DriverManager.getConnection(URL, USER, PASS);
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery("select ename from employee");
			int columnCount = rs.getMetaData().getColumnCount();
			while (rs.next()) {
				System.out.println(rs.getString("ename"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	@Test
	public void useDBUtil() {
		//https://codezine.jp/article/detail/7584
		//https://qiita.com/onsentamushi/items/9abaa443ff86cb0b97cb //<--ここ参考にDTO,DAO作成
		//https://gist.github.com/Kazunori-Kimura/65873596067f8e08407d996dd851dad7

		try {
			conn = DriverManager.getConnection(URL, USER, PASS);
			String sql = "select * from employee";
			PreparedStatement stmt = conn.prepareStatement(sql);
			ResultSet rs = stmt.executeQuery();
			while (rs.next()) {
                String empno =rs.getString("empno");
                String ename = rs.getString("ename");
                System.out.println(empno + ":" + ename);
            }
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}