Cheluis
Cheluis

Reputation: 1412

Problem with ExecuteScalar with Npgsql insert

I', trying to insert a row into a PostgreSQL table with a serial primary key and I need to retrieve this column after it was inserted. I got something like this:

The table "pais" has 3 columns: id, pais, capital; id is a serial column and is its primary key.

NpgsqlCommand query = new NpgsqlCommand("insert into pais(nombre, capital) values(@nombre, @capital)", conn);
query.Parameters.Add(new NpgsqlParameter("nombre", NpgsqlDbType.Varchar));
query.Parameters.Add(new NpgsqlParameter("capital", NpgsqlDbType.Varchar));
query.Prepare();
query.Parameters[0].Value = this.textBox1.Text;
query.Parameters[1].Value = this.textBox2.Text;
Object res = query.ExecuteScalar();
Console.WriteLine(res);

It inserts the row on the table but "res" value is null. If I insert with the nexval('table_sequence') also returns null.

Any idea of how can I return the id of the table? I am missing something?

Thanks in advance

Upvotes: 0

Views: 1204

Answers (1)

Cheluis
Cheluis

Reputation: 1412

It was answered here. The way is using a "Select currval()" or a "Select lastval()" just after the insert statement.

Upvotes: 1

Related Questions