为什么我不能从NPGSQL服务器获取数据?

时间:2019-07-09 08:58:37

标签: c# .net database server npgsql

我需要编写一个C#程序,它必须能够管理我的服务器上的数据。我有一个设置有数据表的NPGSQL服务器,我可以向其中写入数据,但是我在运行程序时无法读取数据。我该怎么办?

 public NpgsqlDataReader reader;
    public NpgsqlCommand InsertCommand = new NpgsqlCommand();
    public String sConnectionString;
    public Npgsql.NpgsqlConnection Conn;
    public void DataBaseOpen()
    {
        sConnectionString = "Server=192.168.1.100;Port=5432;Username=postgres;Password=admin;Database=analoginput;Pooling=false;MinPoolSize=1;MaxPoolSize=999;Timeout=15;";

    Conn = new Npgsql.NpgsqlConnection(sConnectionString);

    InsertCommand = Conn.CreateCommand();
    Conn.Open();
    }

  public void DataBaseClose()
        {
        Npgsql.NpgsqlConnection.ClearAllPools();
        Conn.Close();
        }

InsertCommand.CommandText = "Select * From public.sensorlog WHERE \"date\" > '2019.07.08.' And \"date\" < '2019.07.10.' order by Date asc;";
            System.Windows.MessageBox.Show(InsertCommand.CommandText);
            Npgsql.NpgsqlDataReader reader = InsertCommand.ExecuteReader();
            System.Data.DataTable CSV = new System.Data.DataTable();
            while (reader.Read())
            {
                CSV.Load(reader);
            }

我想将数据加载到CSV数据表中,但是我无法使其正常工作。数据表只是空的。

1 个答案:

答案 0 :(得分:0)

如果将代码重构为如下所示,该怎么办。

using语句将确保您的连接和命令超出范围时将被关闭/处置,并且使用try / catch块将捕获任何异常并通过消息框将其报告给UI。如果有异常,这将有助于捕获异常。

public Npgsql.NpgsqlConnection DatabaseOpen()
{
    var sConnectionString = "Server=192.168.1.100;Port=5432;Username=postgres;Password=xxx;Database=analoginput;Pooling=false;MinPoolSize=1;MaxPoolSize=999;Timeout=15;";

    var Conn = new Npgsql.NpgsqlConnection(sConnectionString);

    Conn.Open();

    return Conn;
}
public void Main()
{
    try
    {
        using (var conn = DatabaseOpen())
        {
            using (var InsertCommand = conn.CreateCommand())
            {
                InsertCommand.CommandText = "Select * From public.sensorlog WHERE \"date\" > '2019.07.08.' And \"date\" < '2019.07.10.' order by Date asc;";
                System.Windows.MessageBox.Show(InsertCommand.CommandText);
                Npgsql.NpgsqlDataReader reader = InsertCommand.ExecuteReader();
                System.Data.DataTable CSV = new System.Data.DataTable();
                while (reader.Read())
                {
                    CSV.Load(reader);
                }
            }
        }
    }
    catch (Exception ex)
    {
        System.Windows.MessageBox.Show(ex.Message);

    }
    finally
    {
        Npgsql.NpgsqlConnection.ClearAllPools();
    }
}