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로 묶어야함. } } } }
Class.forName()
이 불필요하다. JDBC Class.forName() is no longer required – Mkyong.comstatic {}
영역에 드라이버 클래스 등록 코드 필요static { try { DriverManager.registerDriver(new MyNewDriver()); } catch (SQLException ex) { throw new RuntimeException("Can't register driver!"); } }
BoneCPDataSource.setClientInfo(properties)
로 설정하면 자동으로 Connection.setClientInfo
를 매번 호출하여 지정된 모든 프라퍼티를 세팅해준다.ApplicationName
- The name of the application currently utilizing the connectionClientUser
- The name of the user that the application using the connection is performing work for. This may not be the same as the user name that was used in establishing the connection.ClientHostname
- The hostname of the computer the application using the connection is running on.BoneCPDataSource dataSource = new BoneCPDataSource(); dataSource.setDriverClass(com.mysql.jdbc.Driver.class.getCanonicalName()); dataSource.setUser("root"); dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF8"); dataSource.setLogStatementsEnabled(true); Properties clientInfo = new Properties(); clientInfo.setProperty("ApplicationName", "This is JDBC TEST"); InetAddress addr = InetAddress.getLocalHost(); clientInfo.setProperty("ClientHostname", addr.getHostName()); clientInfo.setProperty("ClientHostaddress", addr.getHostAddress()); dataSource.setClientInfo(clientInfo); Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement(); statement.executeQuery("select * from xxx /* hello world! */"); statement.close(); dataSource.close();
/* ApplicationName=This is JDBC TEST, ClientHostname=kwon37xi-dev, ClientHostaddress=127.0.1.1 */ select * from xxx /* hello world! */
Class.forName(“driverClassFQCN”)
처리 과정이 없어도 자동으로 JDBC Driver를 등록해주는 기능이 있다.META-INF/services/java.sql.Driver
파일이 존재하고 그 안에 Driver Class FQCN이 기입돼 있어야 한다.When the method getConnection is called, the DriverManager will attempt to locate a suitable driver from amongst those loaded at initialization and those loaded explicitly using the same classloader as the current applet or application.
WEB-INF/lib
에 JDBC 드라이버가 있으면 JDBC 드라이버 자동로딩 기능은 작동하지 않는 것으로 보인다.${CATALINA_HOME}/lib
에 두어야 올바로 작동하는 듯 하다.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))); } } }