带有Npgsql插入的ExecuteScalar问题

时间:2011-04-07 15:02:41

标签: c# postgresql

我',尝试使用串行主键在PostgreSQL表中插入一行,我需要在插入后检索该列。我有这样的事情:

表“pais”有3列:id,pais,capital; id是一个串行列,是它的主键。

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

它在表上插入行,但“res”值为null。如果我使用nexval('table_sequence')插入也返回null。

我怎么知道如何返回表的id?我错过了什么?

提前致谢

1 个答案:

答案 0 :(得分:1)

回答here。方法是在插入语句之后使用“Select currval()”或“Select lastval()”。