프로그래밍/C#

[c#] postgresql 연동

ss-pro 2023. 6. 10. 17:20
반응형

C#에서 postgresql을 연동하는 방법입니다. npgsql을 사용하면 되고 ADO.NET과 완벽하게 호환되는 것을 목표로 개발이 되어서 .NET의 데이터베이스 처리하는 부분 거의 동일하게 구현을 하면됩니다. 

1. npgsql설치 
-  Nuget을 이용하여 Npgsql 7.0.4버전을 설치합니다. 설치명령어 : Install-Package Npgsql -Version 7.0.4

2. DB연결 및 데이터 저장,조회
ADO.NET과 동일한 클래스형태로 제공하기 때문에 어렵지 않게 구현이 가능합니다. 클래스명도 앞에 npg항목이 붙었고 나머지는 SqlClient를 사용할때와 동일합니다. 

항목  설명 
NpgsqlConnection posetgresql 데이터베이스에 대한 연결
NpgsqlCommand 데이터베이스에 대해 실행할 SQL문이나 저장 프로시저
NpgsqlDataReader 데이터베이스에서 행의 앞으로만 이동 가능한 스트림을 읽을 수 있게
NpgsqlDataAdapter 데이터를 클라이언트에 가져오고 DataSet에 할당 후 연결을 끊고 사용

소스코드를 한번 보면 이해가 쉽게 될겁니다. PostgresqlLib라는 클래스를 생성합니다.  ADO.NET사용하는법과 동일합니다. Connection개체로 DB를 연결하고 Command개체로 SQL문을 입력하여 데이터를 읽고,쓰기를 합니다. 

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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using Npgsql;
 
namespace PostgresqlInferface
{
    class PostgresqlLib
    {
        // 접속테스트
        public bool ConnectionTest()
        {
            string connectString = string.Format("Host={0};Database={1};Username ={2};Password={3};""127.0.0.1",
 "TESTDB""test""1234!");
            try
            {
                using (NpgsqlConnection conn = new NpgsqlConnection(connectString))
                {
                    conn.Open();
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
 
        //데이터조회
        public void SelectDB()
        {
            string connectString = string.Format("Host={0};Database={1};Username ={2};Password={3};""127.0.0.1",
 "TESTDB""test""1234!");
            string sql = "select * from UserInfo";
 
            using (NpgsqlConnection conn = new NpgsqlConnection(connectString))
            {
                conn.Open();
 
                NpgsqlCommand cmd = new NpgsqlCommand(sql, conn);
                NpgsqlDataReader dr = cmd.ExecuteReader();
                dr.Close();
            }
        }
 
        //INSERT처리
        public void InsertDB(int id, string name)
        {
            string connectString = string.Format("Host={0};Database={1};Username ={2};Password={3};""127.0.0.1",
 "TESTDB""test""1234!");
            string sql = $"Insert Into UserInfo  (id,name) values ({id},'{name}')";
 
            using (NpgsqlConnection conn = new NpgsqlConnection(connectString))
            {
                conn.Open();
                NpgsqlCommand cmd = new NpgsqlCommand(sql, conn);
                cmd.ExecuteNonQuery();
            }
        }
 
        //데이터조회
        public DataSet GetUserInfo()
        {
            string connectString = string.Format("Host={0};Database={1};Username ={2};Password={3};""127.0.0.1",
 "TESTDB""test""1234!");
            string sql = "select * from UserInfo";
            DataSet ds = new DataSet();
 
            using (NpgsqlConnection conn = new NpgsqlConnection(connectString))
            {
                conn.Open();
                NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
                da.TableMappings.Add("UserInfo","1");
                da.Fill(ds);
            }
            return ds;
        }
    }
}
cs

윈도우폼 Form1.cs파일을 만듭니다.  테이블을 조회하는 btnSearch버튼과 계정을 추가를 위한 txtId,txtName텍스트박스와 btnAdd버튼을 추가합니다.

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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace PostgresqlInferface
{
    public partial class Form1 : Form
    {
        PostgresqlLib postgresqlLib; 
 
        public Form1()
        {
            InitializeComponent();
        }
 
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
 
            postgresqlLib = new PostgresqlLib();
        }
 
        private void btnAdd_Click(object sender, EventArgs e)
        {
            postgresqlLib.InsertDB(int.Parse(txtID.Text), txtName.Text);
        }
 
        private void btnSearch_Click(object sender, EventArgs e)
        {
            DataSet ds = postgresqlLib.GetUserInfo();
 
            if (ds.Tables.Count > 0)
            {
                dataGridView1.DataSource = ds.Tables[0];
            }
        }
    }
}
 
cs

프로그램을 실행 후 테스트를 해보면 id,name에 값을 입력후 추가하면 UserInfo테이블에 데이터가 저장되고, 조회버튼을 클릭하면 데이터를 가져와 Grid에 표출되는 부분을 확인 할 수 있습니다.


3. Npgsql 상세내용
보다상세한 내용은 아래 npgsql 문서를 참고하면됩니다. https://www.npgsql.org/doc/index.html

반응형