목차

JDBC

Timeout

편리 라이브러리

SQL Logging

Db 접속 테스트. 가장 기본 JDBC 접속 및 쿼리

public class DbTester {
    public static void main(String[] args) throws Exception {
        if (args.length != 4) {
            System.err.println("Usage: java -cp [dbjdbcdriver.jar]:. DbTester [jdbcurl] [db-username] [db-password] [sql]");
        }
        String jdbcUrl = args[0];
        String username = args[1];
        String password = args[2];
        String sql = args[3];
 
        testDb(jdbcUrl, username, password, sql);
    }
 
    public static void testDb(String jdbcUrl, String username, String password, String sql) throws SQLException {
        Connection con = null;
        Statement statement = null;
        try {
            System.out.println(">> Processing JDBC URL : "+ jdbcUrl);
            Class.forName(“driverClassFQCN”); // no need in Java 6/JDBC 4
            con = DriverManager.getConnection(jdbcUrl, username, password);
            statement = con.createStatement();
            boolean executed = statement.execute(sql);
            System.out.println(String.format("Executed '%s' result - %s", sql, executed));
        } finally {
            if (statement != null) {
                con.close(); // 사실은 try/catch로 묶어야함.
            }
            if (con != null) {
                con.close(); // 여기도 try/catch로 묶어야함.
            }
        }
    }
}

JDBC Driver

HA-JDBC

Connection.setClientInfo

JDBC 4 DriverManager

특정 Table 의 meta data 얻기

try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3307/dbname", "username", "password")) {
    final DatabaseMetaData metaData = con.getMetaData();
 
    final ResultSet rs = metaData.getTables(null, null, "[tableName]", new String[] { "TABLE" });
 
    while(rs.next()) {
        final ResultSetMetaData rsMetaData = rs.getMetaData();
        final int columnCount = rsMetaData.getColumnCount();
        for (int i = 1; i <= columnCount; i++) {
            System.out.println("column " + i + ", column name: " + rsMetaData.getColumnName(i) + " , value: " + rs.getString(i)));
        }
    }
}

SQL 생성

참고