How to get the value of selected row from PostgreSQL in C#?

孤街醉人 提交于 2019-12-11 08:58:00

问题


I am using PostgreSQL database with C# and the Npgsql library.

Right now I can select the last row in my table, but I can not figure out how to assign a C# variable to it. I know that my selection works, because I have successfully edited my last entry before.

You can find my code below. Note that I have not pasted the rest of the methods as I think they are irrelevant.

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
    }
}

回答1:


You could achieve this goal by using the specific 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
    }
}

Useful notes

  • In some contexts ExecuteScalar is a good alternative
  • Npgsql documentation



回答2:


Use can use following code variation too;

 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(); 
 }



回答3:


You can use ExecuteScalarSync method.

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
     }
}


来源:https://stackoverflow.com/questions/24053791/how-to-get-the-value-of-selected-row-from-postgresql-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!