본문 바로가기
IT, 개발/JAVA

JAVA - Postgresql 연동 및 조회 쿼리 실행 예제 (JDBC, postgresql, select query 예제)

by 개발자스터디 2022. 12. 8.
반응형

 

 

 

 

 

자바 프로그램을 개발하면서 DB 연동을 하는 일은 아주 많이 있습니다.

 

오늘은 자바에서 Postgresql 연동하는 방법에  대해 알아보도록 하겠습니다.

DB 연결부터 Select 쿼리 실행하는 예제를 살펴보겠습니다.

 

1. 라이브러리

 

우선 라이브러리를 적용해야 합니다.

jar파일이나 dependency를 사용하여 적용합니다.

 

postgresql-42.2.13.jar

 

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.2.13</version>
</dependency>

 

 

2. DB 연결 

 

DB connection 예제입니다.

 

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
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
 
 
public class PostgresqlTest {
        
    // DB Driver
    String dbDriver = "org.postgresql.Driver";
    
    // DB URL
    // IP:PORT/스키마 
    String dbUrl = "jdbc:postgresql://127.0.0.1:54321/dbName";
    
    // DB ID/PW
    String dbUser = "userId";
    String dbPassword = "userPassword";
    
    
    Connection dbconn = null;
    
    
    public void dbConnection()
    {
        Connection connection = null;
        
        try 
        {
            Class.forName(dbDriver);
            connection = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
            dbconn = connection;
            
            System.out.println("DB Connection [성공]");
        } 
        catch (SQLException e) 
        {
            e.printStackTrace();
        } 
        catch (ClassNotFoundException e) 
        {
            e.printStackTrace();
        }
    }
 
}
cs

 

 

 

반응형

 

 

3. Select 예제

 

DB connection 후 연결한 DB의 데이터를 select 할 수 있는 함수가 포함된 예제입니다.

쿼리를 작성하여 호출해보시기 바랍니다.

 

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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
public class PostgresqlTest {
        
    // DB Driver
    String dbDriver = "org.postgresql.Driver";
    
    // DB URL
    // IP:PORT/스키마 
    String dbUrl = "jdbc:postgresql://127.0.0.1:54321/dbName";
    
    // DB ID/PW
    String dbUser = "userId";
    String dbPassword = "userPassword";
    
    
    Connection dbconn = null;
    
    
    public void dbConnection()
    {
        Connection connection = null;
        
        try 
        {
            Class.forName(dbDriver);
            connection = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
            dbconn = connection;
            
            System.out.println("DB Connection [성공]");
        } 
        catch (SQLException e) 
        {
            e.printStackTrace();
        } 
        catch (ClassNotFoundException e) 
        {
            e.printStackTrace();
        }
    }
    
 
    public void dbClose()
    {
        try 
        {
            if(dbconn != null
            {
            dbconn.close();
            dbconn = null;
            System.out.println("DB Close [성공]");
            }
        } 
        catch (SQLException e) 
        {
            e.printStackTrace();
        }
    }
    
 
    
    public List<Object> selectSample(String sql) {
        
        Statement st = null;
 
        Map<String, Object> tempMap = new HashMap<String, Object>();
        List<Object> resultList = new ArrayList<Object>();
        
        try 
        {
            st = dbconn.createStatement();
            ResultSet rs = st.executeQuery(sql);
            
            while (rs.next()) 
            {
                for (int i = 0; i < rs.getMetaData().getColumnCount(); i++
                {
                    tempMap.put(rs.getMetaData().getColumnName(i+1), rs.getString(rs.getMetaData().getColumnName(i+1)));
                }
                
                resultList.add(tempMap);
                tempMap = new HashMap<>();    // tempMap reset
            }
            
            rs.close(); st.close();
        }
        catch (SQLException se1) 
        {
            se1.printStackTrace();
        }
        catch (Exception ex) 
        {
            ex.printStackTrace();
        }
        finally
        {
            try 
            {
                if (st != null)
                {
                    st.close();
                }
            } 
            catch (SQLException se2) 
            { 
                se2.printStackTrace();
            }
        }
        
        return resultList;
    }
    
}
cs

 

 

 

 

 

 

728x90
반응형