Programming/Java
java - mysql jdbc 연결
파란크리스마스
2017. 5. 8. 11:00
728x90
출처 : 초보개발자 이야기. :: JAVA : JDBC를 사용하여 MySQL 과 연동하기 ...
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; public class MySQLJDBCTest { public static void main(String [] args) throws Exception { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { Class.forName("org.gjt.mm.mysql.Driver"); conn = DriverManager.getConnection("jdbc:mysql://bluexmas.tistory.com:3306/test_db", "test", "test"); System.out.println("connection = " + conn); // stmt = conn.prepareStatement("SHOW DATABASES"); rs = stmt.executeQuery(); // ResultSetMetaData rsmd = rs.getMetaData(); int cols = rsmd.getColumnCount(); System.out.printf("The query fetched %d columns\n",cols); System.out.println("These columns are: "); for (int i=1;i<=cols;i++) { String colName = rsmd.getColumnName(i); String colType = rsmd.getColumnTypeName(i); System.out.println(colName+" of type "+colType); } // while (rs.next()) { String str = rs.getNString(1); System.out.println(str); } } catch (SQLException sqex) { System.out.println("SQLException: " + sqex.getMessage()); System.out.println("SQLState: " + sqex.getSQLState()); } finally { if (rs != null) try { rs.close(); } catch (SQLException e) { } if (stmt != null) try { stmt.close(); } catch (SQLException e) { } if (conn != null) try { conn.close(); } catch (SQLException e) { } } } }