Search code examples
c#sqlpostgresqlnpgsql

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


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

Solution

  • 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