Retrieve serial ID with Npgsql when inserting with ExecuteScalar

后端 未结 4 1300
醉酒成梦
醉酒成梦 2020-12-16 19:08

I\'m 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:

Th

相关标签:
4条回答
  • 2020-12-16 19:47

    The insert itself does not cause a value to be returned. When you perform ExecuteScalar it is looking for a single value to be "Selected" so to speak.

    I believe you need to follow up your insert with a select statement to solve your issue.
    If you were using t-sql you would do this like so

    string sql = "INSERT INTO [Table] (FieldName) VALUES (@ParamName); " + "SELECT CAST(scope_identity() AS int)";

    ExecuteScalar would then return the unique id;

    I am not sure of the exact syntax for postGresql but hopefully this allows you to solve your issue.

    0 讨论(0)
  • 2020-12-16 19:49

    Is that thread safe?
    What if another insert happens between your insert and select? Why not use:

    INSERT INTO table (fieldnames) VALUES (values) RETURNING idcolumn?

    0 讨论(0)
  • 2020-12-16 19:56

    In order to select the last identity inserted you need to use: currval(sequencename)

    so your select statement should look like:

    NpgsqlCommand query = new NpgsqlCommand("insert into pais(nombre, capital) values(@nombre, @capital);select currval('table_sequence');", conn);
    
    0 讨论(0)
  • 2020-12-16 20:05
    insert into pais(nombre, capital) values(@nombre, @capital) RETURNING id
    

    replace id with your primary keyenter code here and use

    Object res = query.ExecuteScalar();
    

    Inside res you'll have the PK.

    0 讨论(0)
提交回复
热议问题