JDBC 테스트 소스

POSTGRESQL 2015. 6. 24. 15:07

postgreSQL JDBC 접속테스트 소스입니다.

 

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
  
public class JDBCExample {
  
 public static void main(String[] argv) {
  Connection conn = null;
  Statement  st   = null;
  ResultSet  rs   = null;
 
// connection 속성 설정
  String     url      = "jdbc:postgresql://localhost/postgres";
  String     user     = "postgres";
  String     password = "postgres";
  String    query    = "select version()";
 
  System.out.println("-------- PostgreSQL JDBC Connection Testing ------------");
   
  try {
// postgresql 드라이버 클래스를 JDBC드라이버 메니저에 로드
   Class.forName("org.postgresql.Driver");
  
  } catch (ClassNotFoundException e) {
  
   System.out.println("Where is your PostgreSQL JDBC Driver? "
     + "Include in your library path!");
   e.printStackTrace();
   return;
  
  }
  
  System.out.println("PostgreSQL JDBC Driver Registered!");
  
  //Connection conn = null;
  
  try {
// conncetion establish 하기
   conn = DriverManager.getConnection(url, user, password);
  
  } catch (SQLException e) {
  
   System.out.println("Connection Failed! Check output console");
   e.printStackTrace();
   return;
  
  }
  
  if (conn != null) {
   System.out.println("Connection established!");
  } else {
   System.out.println("Failed to make conn!");
  }
 
// 실행할 쿼리 statement 입력
  try {
   st = conn.createStatement();
   rs = st.executeQuery(query);
   while (rs.next()) {
    String ver = rs.getString("version");
    System.out.println("Your version : " + ver);
   }
  }
  catch (SQLException e ) {
   System.out.println("query execution failed...");
   e.printStackTrace();
                        return;
  }
   
// statement / connection close 하기
  try {
   if (st   != null) { st.close(); }
   if (conn != null) {conn.close(); }
  }
  catch (SQLException e ) {
                        System.out.println("failed to close statement or connection");
                        e.printStackTrace();
                        return;
                }
 } //main end
}// JDBCExample class end