使用Npgsql for Postgresql的C#查询显示重复结果和缺少表数据
作者:互联网
我正在检查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;
}
}
}
}
解决方法:
重复内容的问题是由使用While(dRead.Read())的循环和使用foreach的表的DataRows循环引起的.这有效地在您的数据上循环两次.
如果要使用DataReader循环遍历记录,则不需要DataRow和DataTable,而是使用DataReader的FieldCount属性和DataReader索引器作为当前记录.
// Not needed
// ad.Fill(dt);
NpgsqlDataReader dRead = com.ExecuteReader();
while (dRead.Read())
{
for(int i = 0; i < dRead.FieldCount; i++)
Console.Write("{0} \t \n", dRead[i].ToString());
}
相反,如果你想循环遍历DataTable及其行,则需要使用Columns.Count进行循环
ad.Fill(dt);
// Not needed
// NpgsqlDataReader dRead = com.ExecuteReader();
foreach(DataRow row in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
Console.Write("{0} \t \n", row[i].ToString());
}
}
标签:c,database,postgresql,datasource,npgsql 来源: https://codeday.me/bug/20190624/1275939.html