Postgres connect

S:)·2022년 9월 18일

DB Connection

목록 보기
2/3

postgreSQL

: ADO.NET 과 동일한 클래스 형태로 제공하고 대부분 SQL DB 연결과 동일하다.

1. using Npgsql;
Npgsql NuGet패키지를 참조

2. NpgsqlConnection
: postgresql 접속하기 위한 클래스

  • 서버와 접속하기 위해서는 ConnectionString이 필요
  • ConnectionString 에는 HOST IP , PORT , 서버명 , 비밀번호, 초기DB명 지정
  public void DBConnection()
  {
     private string ConnectionString;
     private NpgsqlConnection sqlConn;  
    //POSTGRESQL DB 연결
     ConnectionString = "HOST=127.0.0.1;PORT=5432;USERNAME=postgres;PASSWORD=postgres;DATABASE=postgres"; 
    //POSTGRESQL DB 오픈
    sqlConn = new NpgsqlConnection(ConnectionString);
    try
    {
        sqlConn.Open();             
    } 
  }

3. NpgsqlCommand : 데이터베이스에 대해 실행할 SQL문이나 저장 프로시저

  • NpgsqlCommand.ExecuteNonQuery : INSERT, UPDATE, DELETE 등의 DML 문장을 실행할 때 사용
 using (NpgsqlConnection conn = new NpgsqlConnection(connectString))
 {
 				string sql = "insert into table1 ~";
                conn.Open(); 
                NpgsqlCommand cmd = new NpgsqlCommand(sql, conn);
                cmd.ExecuteNonQuery();
 }
  • NpgsqlCommand.ExecuteReader : 데이터를 서버에 가져오는 SELECT 문장을 실행할 때 사용
    -DataReader는 하나의 Connection 에 하나만 Open 되어 있어야 하여 , 사용이 끝나면 Close()를 호출 하여 닫아줘야 한다.
 using (NpgsqlConnection conn = new NpgsqlConnection(connectString))
 {
 				string sql = "select * from table1";
                conn.Open(); 
                NpgsqlCommand cmd = new NpgsqlCommand(sql, conn);
                NpgsqlDataReader dr = cmd.ExecuteReader();
                dr.Close();
}

4. NpgsqlDataAdapter vs NpgsqlDataReader

  • 연결
    NpgsqlDataAdapter : 데이터를 가져온 후 연결을 끊고 데이터 사용
    NpgsqlDataReader : 연결을 유지

  • 데이터 형태
    NpgsqlDataAdapter : DataSet (그리드 같은 컨트롤에 데이터 바인딩 소스로 활용)
    NpgsqlDataReader : 한 행씩(row)

  string sql = "select * from table1";
  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);
  }

ex) 사용예시

using System;
using Npgsql;

namespace npgsql_test
{
    class Program
    {
        static void Main(string[] args)
        {

            using (var conn = new NpgsqlConnection("Host=localhost;Username=postgres;Password=1234;Database=test2db"))
            {
                try
                {
                    conn.Open();
                    using (var cmd = new NpgsqlCommand())
                    {
                        cmd.Connection = conn;

                        cmd.CommandText = "select * from addresses";

                        using (var reader = cmd.ExecuteReader())
                        {
                            Console.WriteLine("table column 수 = {0} 개", reader.FieldCount); 

                            while (reader.Read())
                            {
                                // 각각의 항목 읽어 들이는 방법들...
                                // Console.WriteLine(reader.GetString(0));
                                // Console.WriteLine(reader.GetValue(3));
                                // Console.WriteLine(reader["email_address"] as string);

                                var data = new string[] { reader["id"].ToString(),
                                reader["email_address"].ToString(),
                                reader["user_id"].ToString(),
                                reader["createtime"].ToString() };

                                foreach (var x in data)
                                {
                                    Console.Write(x);
                                    Console.Write(" -- ");
                                }
                                Console.WriteLine();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("============== Error ==============");
                    Console.WriteLine(ex.Message);
                }
            }

            Console.ReadLine();

        }
    }
}
profile
일단 저장

0개의 댓글