MySql 쿼리 결과 출력하기

import java.sql.*;
import java.util.ArrayList;

public class JdbcTest {

	private String URL = "jdbc:mysql://localhost";
	private String USERNAME = "user";
	private String PASSWORD = "password";
	private Connection conn;
	public JdbcTest(){
		openConnection();
	}

	public void openConnection(){
		try{
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			conn=DriverManager.getConnection(URL,USERNAME,PASSWORD);
			if(!conn.isClosed())
				System.out.println("Successfully connected to "+ "MySQL server using TCP/IP...");
		}catch(Exception e){
			System.err.println("Exception : "+e.getMessage());
		}
	}

	public void close(){
		try{
			if(conn!=null) conn.close();
		}catch(SQLException e){}
	}

	private void writeResultSet(ResultSet resultSet) throws SQLException {
		int columnCount = resultSet.getMetaData().getColumnCount();
		if (columnCount<1) return;
		System.out.println("--------------------------------------");
		ArrayList <String> labels = new ArrayList<String>();
		for  (int i = 1; i<= columnCount; i++){
			String label = resultSet.getMetaData().getColumnLabel(i);
			System.out.print(label+"\t");
			labels.add(label);
		}
		System.out.println("\n--------------------------------------");
		while(resultSet.next()){
			for(String label:labels)
				System.out.print(resultSet.getString(label)+"\t");
			System.out.println();
		}
		System.out.println("--------------------------------------\n");
	}

	private void executeQuery(String query){
		System.out.println("Execute Query : "+query);
		try{
			Statement st=conn.createStatement();
			ResultSet resultSet = st.executeQuery(query);
			writeResultSet(resultSet);
			resultSet.close();
			st.close();
		}catch(Exception e){
			System.out.println("Exception : "+e.getMessage());
		}
	}
	public static void main(String [] args){
		JdbcTest db = new JdbcTest();
		db.executeQuery("show databases;");
		db.executeQuery("use mysql");
		db.executeQuery("show tables;");
		db.executeQuery("select * from user;");
		db.close();
	}
}
Posted by 김민우 julingks
TAG , ,