我,试图插入一行到PostgreSQL的表串行主键,我需要检索此列插入之后。我是这样的:
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:
表国家报有3列:ID,派斯,资本; id是一个串行列,是它的主键。
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);
它插入该行的表,但资源的价值是零。如果我插入的nexval('table_sequence)也将返回null。
It inserts the row on the table but "res" value is null. If I insert with the nexval('table_sequence') also returns null.
我怎么可以返回表的ID你知道吗?我失去了一些东西?
Any idea of how can I return the id of the table? I am missing something?
在此先感谢
为了选择插入你需要使用的最后一个标识: CURRVAL(sequencename)
In order to select the last identity inserted you need to use: currval(sequencename)
让你的SELECT语句应该是这样的:
so your select statement should look like:
NpgsqlCommand query = new NpgsqlCommand("insert into pais(nombre, capital) values(@nombre, @capital);select currval('table_sequence');", conn);
您可以找到这个多在的http://www.programmingado.net/a-117/Insert-data-and-retrieve-serial-autonumber-id.aspx
干杯,
CEC