티스토리 뷰

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) { }
		}
	}

}
댓글
300x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함