欢迎投稿

今日深度:

c# 访问postgressql,使用pghelper访问pgsql,

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。使用习惯看个人吧。

好了,就写到这里了,不当之处还请各位看官体谅

 

www.htsjk.Com true http://www.htsjk.com/postgresSQL/10384.html NewsArticle c# 访问postgressql,使用pghelper访问pgsql, 由于工作需要,数据库是postgressql的,本来以为很简单的,结果弄了一晚上,为了总结经验,现将C#连接PGSQL(postgres sql)的资料整理如下。 一、...
相关文章
    暂无相关文章
评论暂时关闭