c# 訪問postgressql,使用pghelper訪問pgsql


由於工作需要,數據庫是postgressql的,本來以為很簡單的,結果弄了一晚上,為了總結經驗,現將C#連接PGSQL(postgres sql)的資料整理如下。

一、總體思路

1、通過第三方Npgsql的的dll實現數據庫的連接。

2、連接文件寫在web.config中。

3、連接類寫成pghelper。

這樣,在程序中,可以像sqlhelper一樣調用了。

二、下載資料

1、Npgsql的下載地址http://pgfoundry.org/projects/npgsql/,

2、當然,你需要安裝postgres sql,去官網下載安裝,過程略。

三、配置與代碼

1、web.config 中,配置<connectionStrings>

放於<configuration></configuration>內任何位置均可。

樣本如下:

<configuration>

  <connectionStrings>

       <add name="postgre" connectionString="PORT=5433;DATABASE=test;HOST=localhost;PASSWORD=123;USER ID=postgres"/>
      </connectionStrings>

</configuration>

解釋connectionString里存的就是連接PG數據庫的配置信息了,具體略。

2、寫一個pghelper類。

在類中,插入如何下的方法:

 public static string ConnectionString = ConfigurationManager.ConnectionStrings["postgre"].ToString();   
      

        /// <summary>  
        /// 執行SQL語句  
        /// </summary>  
        /// <param name="sql">SQL</param>  
        /// <returns>成功返回大於0的數字</returns>  
        public static int ExecuteSQL(string sql)
        {
            int num2 = -1;
            using (NpgsqlConnection connection = new NpgsqlConnection(ConnectionString))
            {
                using (NpgsqlCommand command = new NpgsqlCommand(sql, connection))
                {
                    try
                    {
                        connection.Open();
                        num2 = command.ExecuteNonQuery();
                    }
                    catch (NpgsqlException exception)
                    {
                        throw new Exception(exception.Message);
                    }
                    finally
                    {
                        connection.Close();
                    }
                }
            }
            return num2;
        }

        //帶參數的執行查詢,不返回結果,返回影響行數
        //執行SQL語句並返回受影響的行數
        public static int ExecuteNonQuery(string sql, params NpgsqlParameter[] parameters)
        {
            using (NpgsqlConnection conn = new NpgsqlConnection(ConnectionString))
            {
                conn.Open();
                using (NpgsqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = sql;
                    //foreach (SqlParameter param in parameters)
                    //{
                    //    cmd.Parameters.Add(param);
                    //}
                    cmd.Parameters.AddRange(parameters);
                    return cmd.ExecuteNonQuery();
                }
            }
        }

        //執行查詢,並返回查詢所返回的結果集中第一行的第一列。忽略額外的列或行。
        public static object ExecuteScalar(string sql, params NpgsqlParameter[] parameters)
        {
            using (NpgsqlConnection conn = new NpgsqlConnection(ConnectionString))
            {
                conn.Open();
                using (NpgsqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = sql;
                    cmd.Parameters.AddRange(parameters);
                    return cmd.ExecuteScalar();                    
                    
                }
            }
        }


       

        //查詢並返回結果集DataTable,一般只用來執行查詢結果比較少的sql。
        public static DataTable ExecuteDataTable(string sql, params NpgsqlParameter[] parameters)
        {
            using (NpgsqlConnection conn = new NpgsqlConnection(ConnectionString))
            {
                conn.Open();
                using (NpgsqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = sql;
                    cmd.Parameters.AddRange(parameters);

                    NpgsqlDataAdapter adapter = new NpgsqlDataAdapter(cmd);
                    DataSet dataset = new DataSet();
                    adapter.Fill(dataset);
                    return dataset.Tables[0];
                }
            }

            //查詢較大的數據用 DateRead(),但應盡可能用分頁數據,仍然用datatable更好。
        }

 

四、使用。

   使用時,就可以像SQLHELPER一樣用了。

int i;
            i = pghelper.ExecuteSQL("update student set classid=113 where id=4");
            context.Response.Write("這是無參數的ExecuteSQL:" + i + "<br/>");
            
            i = pghelper.ExecuteNonQuery("update student set classid=113 where id=@id", new NpgsqlParameter("@id", 4));
            context.Response.Write("這是有參數的調用ExecuteNonQuery:" + i + "<br/>");

            string s = pghelper.ExecuteScalar("select count(name) from student").ToString();
            context.Response.Write("這是exeScalar調用:" + s+"<br/><hr/>");

            DataTable dt = new DataTable();
            dt = pghelper.ExecuteDataTable("select id,name from student");
            context.Response.Write("這是ExecuteDataTable:<br/>");

            for (int j=0;j<dt.Rows.Count;j++)
            {
                DataRow dr = dt.Rows[j];
                context.Response.Write(dr["id"].ToString()+dr["name"].ToString());
            }

其實,ExecuteNonQuery完全可以取代ExecuteSQL。使用習慣看個人吧。

好了,就寫到這里了,不當之處還請各位看官體諒

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM