1.C#连接PostgreSQL数据库需要两个组件:Npgsql.dll和Mono.Security.dll。下载地址:https://pan.baidu.com/s/1ZFGm2tbZJUGnjmt6uLnASw
2.C#工程里引用上述组件,在需要使用Npgsql的C#文件头加入using Npgsql ;
3.在配置文件中配置连接字符串,如下:
<!--要访问的数据库IP地址、端口号、数据库名称、数据库登陆名、密码。加上Encoding避免乱码>
<connectionStrings>
<add name="PostgreSQL" connectionString="Server=localhost;Port=5432;UserId=admin;Password=admin;Database=test;Encoding=UNICODE;">
</connectionStrings>
获取连接字符串:public static string connection_pgsql = ConfigurationManager.ConnectionStrings["PostgreSQL"].ToString();
4.获取DataSet
public DataSet GetDataSet(string sql)
{
try
{
using (NpgsqlConnection conn = new NpgsqlConnection(connection_pgsql ))
{
conn.Open();
NpgsqlCommand cmd = new NpgsqlCommand(sql, conn);
NpgsqlDataAdapter NpgDa = new NpgsqlDataAdapter(cmd);
DataSet ds = new DataSet();
NpgDa.Fill(ds);
return ds;
}
}
catch (Exception ex)
{
return new DataSet();
}
}
5.增删改
public int ExecuteNonQuery(string sql)
{
try
{
using (NpgsqlConnection conn = new NpgsqlConnection(connection_pgsql ))
{
conn.Open();
NpgsqlCommand cmd = new NpgsqlCommand(sql, conn);
int r = cmd .ExecuteNonQuery(); //执行查询并返回受影响的行数
conn.Close();
return r;
}
}
catch (Exception ex)
{
return 0;
}
}
网友评论