【发布时间】:2015-03-11 20:44:49
【问题描述】:
我正在检查 PostgreSQL 作为 SQLServer 的潜在替代品,我在 PostgreSQL 公共架构的测试数据库中创建了一个测试表,并向测试表添加了两行数据。
现在的问题是,当使用 NpgSQL.dll 从 C#.net 运行简单查询时,我得到重复的结果,并且并未显示所有表数据。
这是我使用的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using Npgsql;
namespace PlayingWithPostgres
{
class Program
{
static void Main(string[] args)
{
// creating the connection string (Server, Port, User id, password, database)
string conStr = "Server=127.0.0.1; Port=5432; User Id=postgres; Password=Sada1973; Database=CarsTestDB;";
NpgsqlConnection conn = new NpgsqlConnection(conStr);
string comStr = "Select * FROM \"CarsTable\";";
NpgsqlCommand com = new NpgsqlCommand(comStr, conn);
NpgsqlDataAdapter ad = new NpgsqlDataAdapter(com);
DataTable dt = new DataTable();
Console.WriteLine("Conection to server established successfuly \n");
// check if connection is open or not
if(conn != null && conn.State == ConnectionState.Open)
{
Console.WriteLine("Connection Open");
conn.Close();
}
else
{
conn.Open();
}
// Fill data table with data and start reading
ad.Fill(dt);
NpgsqlDataReader dRead = com.ExecuteReader();
try
{
Console.WriteLine("Contents of table in database: \n");
while (dRead.Read())
{
foreach(DataRow row in dt.Rows)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Console.Write("{0} \t \n", row[i].ToString());
}
}
}
}
catch (NpgsqlException ne)
{
Console.WriteLine("Problem connecting to server, Error details {0}", ne.ToString());
}
finally
{
Console.WriteLine("Closing connections");
dRead.Close();
dRead = null;
conn.Close();
conn = null;
com.Dispose();
com = null;
}
}
}
}
【问题讨论】:
标签: c# database postgresql datasource npgsql