我试图在一个带有串行主键的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);
Run Code Online (Sandbox Code Playgroud)
它在表上插入行,但"res"值为null.如果我使用nexval('table_sequence')插入也返回null.
知道怎样才能返回表的id?我错过了什么吗?
提前致谢
hsm*_*ths 16
这个线程安全吗?
如果在插入和选择之间发生了另一次插入怎么办?为什么不使用:
INSERT INTO table (fieldnames) VALUES (values) RETURNING idcolumn?
小智 10
insert into pais(nombre, capital) values(@nombre, @capital) RETURNING id
Run Code Online (Sandbox Code Playgroud)
替换id为您的主键enter code here并使用
Object res = query.ExecuteScalar();
Run Code Online (Sandbox Code Playgroud)
在里面res你会有PK.
要选择插入的最后一个标识,您需要使用: currval(sequencename)
所以你的select语句应如下所示:
NpgsqlCommand query = new NpgsqlCommand("insert into pais(nombre, capital) values(@nombre, @capital);select currval('table_sequence');", conn);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12413 次 |
| 最近记录: |