在c#中,利用npgsql连接postgresql

来源:互联网 发布:手机映射软件下载 编辑:程序博客网 时间:2024/06/10 21:06

1。加载Npgsql.dll文件

 

。在Web.config中添加

<add key="ConnectionString" value="Server=127.0.0.1;Port=5432;User   Id=postgres;Password=postgres;Database=gis;Encoding=UNICODE"/>

 

2。从web.config文件中读取信息

//不要忘记

using Npgsql;
using System.Web.Configuration;

 

 public static string GetAppSetting(string key)
    {
        string value = WebConfigurationManager.AppSettings[key];
        if(value == null)
        {
            throw new ConfigurationErrorsException("Error!");
        }
        return value;
   }

public static string ConnectionString
        {
            get
            {
                return GetAppSetting("ConnectionString");
            }
        }

 

3。连接数据库

 

protected NpgsqlConnection GetDBConnection()
        {
            NpgsqlConnection connect;

            connect = new NpgsqlConnection(ConnectionString);
            connect.Open();

            return connect;
        }

 

以后用的时候直接 NpgsqlConnection  conn=GetDBConnection();是不是很方便。。。