如何从C#中的PostgreSQL中获取所选行的值?

时间:2014-06-05 07:08:46

标签: c# sql postgresql npgsql

我正在使用带有C#的PostgreSQL数据库和Npgsql库。

现在我可以选择表格中的最后一行,但我无法弄清楚如何为它分配C#变量。我知道我的选择有效,因为我之前已成功编辑了我的最后一个条目。

您可以在下面找到我的代码。请注意,我没有粘贴其他方法,因为我认为它们无关紧要。

public void myMethod()
{
    this.OpenConn(); //opens the connection

    string sql = "SELECT id FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'customers' ORDER BY id DESC, LIMIT 1";

    using (NpgsqlCommand command = new NpgsqlCommand(sql, conn))
    {
        int id = 0; //instead of '0' I want it to be equal to the ID value from the row
        //something like "int id = sqlSelection.id;" -- this obviously doesn't work

        this.CloseConn(); //close the current connection
    }
}

3 个答案:

答案 0 :(得分:4)

您可以使用特定的 DataReader

来实现此目标
public void myMethod()
{
    this.OpenConn(); //opens the connection

    string sql = "SELECT id FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'customers' ORDER BY id DESC, LIMIT 1";

    using (NpgsqlCommand command = new NpgsqlCommand(sql, conn))
    {
        int val;
        NpgsqlDataReader reader = command.ExecuteReader();
        while(reader.Read()){
           val = Int32.Parse(reader[0].ToString());
           //do whatever you like
        }

        this.CloseConn(); //close the current connection
    }
}

有用的笔记

答案 1 :(得分:0)

使用也可以使用以下代码变体;

 using (var command = new NpgsqlCommand(sql, conn))
 {
        int id = 0; 
        var reader = command.ExecuteReader();
        while(reader.Read())
        { 
           var id = Int32.Parse(reader["id"].ToString());
        }
        this.CloseConn(); 
 }

答案 2 :(得分:0)

您可以使用ExecuteScalarSync方法。

public void myMethod()
{
    this.OpenConn(); //opens the connection

    string sql = "SELECT id FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'customers' ORDER BY id DESC, LIMIT 1";

    using (NpgsqlCommand command = new NpgsqlCommand(sql, conn))
     {
       int id= (int)DBHelperRepository.ExecuteScalarSync(sqlString, CommandType.Text);

       this.CloseConn(); //close the current connection
     }
}