MisoBoy Blog...

[20110715] Java JDBC (JDBC 로 ORACLE 연동하여 ZIPCODE 프로그램) 본문

Java

[20110715] Java JDBC (JDBC 로 ORACLE 연동하여 ZIPCODE 프로그램)

misoboy 2011. 7. 15. 15:31
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;

// 1. import
public class JDBCDemo1 {
	public static void main(String [] args){
		// 2. Driver Loading
		try{
			Class.forName("oracle.jdbc.driver.OracleDriver");
			System.out.println("Driver loading Success");
		}catch(ClassNotFoundException ex){
			System.out.println("Class Not Found");
		}
		// 3. DB Connection
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try{
			conn = DriverManager.getConnection
			("jdbc:oracle:thin:@192.168.0.94:1521/ORCL", "scott", "tiger");
			System.out.println("Connection Success");
			// 4. Statement 객체 생성
			stmt = conn.createStatement();
			// 5. Query 실행
			String dongName = JOptionPane.showInputDialog
			("찾고자 하는 이름을 입력하세요 : ").trim();
			String sql = "SELECT zipcode, sido, gugun, dong, bunji ";
			sql += "FROM zipcode where dong LIKE '%" + dongName + "%'";
			//System.out.println("sql = " + sql);						
			//코딩하는 중간 중간에 TEST 해보는게 좋다
			rs = stmt.executeQuery(sql);			// select 할때 사용
			//stmt.executeUpdate(sql);		// update 할때 사용
			while(rs.next()){
				String zipcode = rs.getString(1);		// 컬럼 위치별로 지정을 한다.
				String sido = rs.getString("sido");		
				// 컬럼명으로 작성한다면 더욱 명확 해지므로 사용해도 된다.
				String gugun = rs.getString(3);
				String dong = rs.getString("dong");
				String bunji = rs.getString(5);
				System.out.println
				(zipcode+ " " +sido+ " " +gugun+ " " +dong+ " " +dong+ " " +bunji);
			}
		}catch(SQLException ex){
			ex.printStackTrace();					
			// 에러 메세지의 발생 근원지를 찾아서 단계별로 에러를 출력한다.
		}finally{
			// 7. DB Close
			try{
				if(rs != null) rs.close();			// ResultSet 을 닫는다.
				if(stmt != null) stmt.close();		// Statement 을 닫는다.
				if(conn != null) conn.close();		// Connection 을 닫는다.
			}catch(SQLException ex){}
		}
	}
}