java - mysql jdbc 연결

Programming/Java 2017.05.08 11:00 Posted by 파란크리스마스

출처 : 초보개발자 이야기. :: 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) { }
		}
	}

}
저작자 표시
신고


 

티스토리 툴바