본문 바로가기
[ DataBase ]/PostgreSQL

[PostgreSQL] c# 연동 / 이미지저장

by 관이119 2023. 3. 2.

그림1

 

새프로젝트를 만들고 그림1과 같이 Nuget패키지관리자를 실행하자.

 

그림2

 

그림2와 같이 npgsql 을 검색해서 패키지를 설치하자. ( 이때 필요한 DLL 들이 전부 추가된다.)

 

그림3

 

설치를 누르면 그림3과 같이 필요한 내용들이 표시되고 설치되고 참조가 추가되게 된다.

 

 

 

 

그림4

 

UI는 그림4와 같이 만들어줬다.

 

 

using Npgsql;
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 PostgresSQLSample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btn_Select_Click(object sender, EventArgs e)
        {
            string connectionString = "Host=127.0.0.1;Port=5432;Database=postgres;User ID=postgres;Password=test";

            DataTable result = new DataTable();
            result.Columns.Add("testcol1");
            result.Columns.Add("testcol2");

            using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
            {
                

                try
                {
                    connection.Open();

                    using (NpgsqlCommand command = new NpgsqlCommand())
                    {
                        command.Connection = connection;
                        command.CommandText = "SELECT * FROM testtable";

                        using (NpgsqlDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                DataRow dr = result.NewRow();
                                dr.ItemArray = new object[] { reader["testcol1"].ToString(), reader.GetString(1) };
                                result.Rows.Add(dr);
                            }
                        }
                    }

                    dataGridView1.DataSource = result;
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.ToString());
                }
            }
        }
    }
}

전체코드는 위와 같다.

 

테이블 만드는법은 이미 설치편에서 진행해서 따로 내용을 넣지는 않았다.

실행하면 그리드에 테이블의 내용이 표시되는걸 확인할 수 있다.

 

 

 

 

-----------------------------------------------------------------------------------------------------------------------------------------------------

 

 

그림5

이미지저장을 위해 그림5와 같이 bytea 타입의 컬럼을 추가해준다.

 

 

그림6

 

UI 는 그림6과 같이 변경해줬다.

 

using Npgsql;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PostgresSQLSample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btn_Select_Click(object sender, EventArgs e)
        {
            string connectionString = "Host=127.0.0.1;Port=5432;Database=postgres;User ID=postgres;Password=test";

            DataTable result = new DataTable();
            result.Columns.Add("testcol1");
            result.Columns.Add("testcol2");

            using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
            {
                

                try
                {
                    connection.Open();

                    using (NpgsqlCommand command = new NpgsqlCommand())
                    {
                        command.Connection = connection;
                        command.CommandText = "SELECT * FROM testtable";

                        using (NpgsqlDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                DataRow dr = result.NewRow();
                                dr.ItemArray = new object[] { reader["testcol1"].ToString(), reader.GetString(1) };
                                result.Rows.Add(dr);
                            }
                        }
                    }

                    dataGridView1.DataSource = result;
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.ToString());
                }
            }
        }

        private void btn_insert_Click(object sender, EventArgs e)
        {
            string connectionString = "Host=127.0.0.1;Port=5432;Database=postgres;User ID=postgres;Password=test";

            using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
            {
                try
                {
                    connection.Open();

                    using (NpgsqlCommand command = new NpgsqlCommand())
                    {
                        command.Connection = connection;
                        command.CommandText = "INSERT INTO public.testtable (testcol1, testcol2, testcol3) VALUES(@A, @B, @C);";
                        command.Parameters.AddWithValue("A", "test11");
                        command.Parameters.AddWithValue("B", "test21");

                        using (MemoryStream ms = new MemoryStream())
                        {
                            pic_insertbox.Image.Save(ms, ImageFormat.Bmp);
                            command.Parameters.AddWithValue("C", ms.ToArray());
                            command.ExecuteNonQuery();
                        }
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.ToString());
                }
            }
        }

        private void btn_load_Click(object sender, EventArgs e)
        {
            string connectionString = "Host=127.0.0.1;Port=5432;Database=postgres;User ID=postgres;Password=test";

            using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
            {
                try
                {
                    connection.Open();

                    using (NpgsqlCommand command = new NpgsqlCommand())
                    {
                        command.Connection = connection;
                        command.CommandText = "select testcol3 from public.testtable WHERE testcol1 = 'test11'";

                        using (NpgsqlDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                byte[] imagebytear = (byte[])reader["testcol3"];
                                using (MemoryStream ms = new MemoryStream(imagebytear))
                                {
                                    Image img = Image.FromStream(ms);
                                    pic_loadbox.Image = img;
                                }
                            }
                        }
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.ToString());
                }
            }
        }
    }
}

소스는 위와 같이 변경해줬다.

insert 에서 왼쪽에 있는 이미지를 인서트 하고 오른쪽 load 를 누르면 오른쪽 픽쳐박스에 저장된 이미지를 로드해오게 된다.

댓글