C#postgres数据库连接
问题描述:
我已经设法连接到数据库,但我使用下面的代码进行连接。C#postgres数据库连接
static void Main(string[] args)
{
using (NpgsqlConnection conn= new NpgsqlConnection(
"Host=xxx.xx.xx.xxx;Port=5432;User Id=Admin;Password=postgres.1;Database=Test1;"))
{
conn.Open();
NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM TABLE1", conn);
try
{
NpgsqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
for (int i = 0; i < dr.FieldCount; i++)
{
Console.Write("{0} \t", dr[i]);
}
Console.WriteLine();
}
dr.Close();
}
finally
{
conn.Close();
}
}
Console.ReadLine();
}
显然,我必须以某种方式生成的数据库中的表类,并使用这些连接,而不是使用NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM TABLE1", conn);
。已尝试使用DbLinq的DbMetal,但我收到错误消息:
DbMetal:服务器已关闭连接。
我一直在研究这个,但我还没有找到任何有用的东西。
如果可以,请帮助。这有点紧急。
在此先感谢。
答
我想你需要一个NpgsqlDataAdapter和
DataSet ds = new DataSet();
NpgsqlDataAdapter da = new NpgsqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
return ds;
现在您的DataSet包含一个表中选择(ds.Tables [0])和表中的所有行的数据集
foreach(DataRow r in ds.Tables[0].Rows)
Console.WriteLine(r["ColumnName"].ToString());
HTTP:/ /romain.blogreen.org/blog/2009/07/linq-postgresql-and-mono/可能这会有所帮助 – horgh 2012-08-08 07:28:56
小心:DbLinq可能是越野车! – linquize 2012-08-08 07:40:23
@horgh这些是我遵循的指示。尝试了CMD和单声道。它连接了一秒钟,然后失去连接 – robertpas 2012-08-08 07:49:09