2018年9月26日

PostgreSQL 連線,存取資料方式。使用 C# WinFrom


NuGet 安裝 Npgsql。 (圖1)

圖1



        NuGet 安裝 Npgsql。(圖2)


圖2


安裝成功後,「參考」會有 Npgsql(圖3)
圖3

使用 ConfigurationManager 需加入 System.configuration 至「參考」 (圖4)

圖4


======= 程式範例 回傳 DataTable

       public static DataTable Npgsql_Data(String sql)
       {
           //參考資料
           //https://www.npgsql.org/doc/index.html
           String connstr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

           DataTable dt = new DataTable();
           using (Npgsql.NpgsqlConnection conn = new Npgsql.NpgsqlConnection(connstr))
           {
               conn.Open();
               using (var cmd = new Npgsql.NpgsqlCommand())
               {
                   cmd.Connection = conn;
                   cmd.CommandText = sql;
                   //執行不Query的方式
                   //cmd.ExecuteNonQuery();
                   Npgsql.NpgsqlDataReader dr = cmd.ExecuteReader();
                   dt.Load(dr);
               }
           }

           return dt;

       }


======= 程式範例 回傳 bool

       public static bool Npgsql_Data(String sql,String id,String value,String point)
       {
           bool success = false;
           //https://www.npgsql.org/doc/index.html
           String connstr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

           DataTable dt = new DataTable();
           using (Npgsql.NpgsqlConnection conn = new Npgsql.NpgsqlConnection(connstr))
           {
               conn.Open();
               using (var cmd = new Npgsql.NpgsqlCommand())
               {
                   cmd.Connection = conn;
                   cmd.CommandText = sql;
                   cmd.Parameters.AddWithValue("id", id);
                   cmd.Parameters.AddWithValue("value", value);
                   cmd.Parameters.AddWithValue("point", point);
                   if(cmd.ExecuteNonQuery() > 0)
                   {
                       success = true;
                   }else
                   {
                       success = false;
                   }
                   
               }
               
           }
           return success;
       }

沒有留言:

張貼留言