Return Value ID C# Npgsqlcommand

Asked

Viewed 311 times

2

After inserting a row of information in a given table, I need to recover the ID value to fill my object, my code is like this:

using (NpgsqlConnection pgsqlConnection = new NpgsqlConnection(conn)
        {           
            pgsqlConnection.Open();
            String sql = "INSERT INTO public.localpo(NOME) VALUES (:nome)";
            using (NpgsqlCommand pgsqlcommand = new NpgsqlCommand(sql, pgsqlConnection))
            {
    pgsqlcommand.Parameters.Add(new NpgsqlParameter("nome", "Ricardo Soares"));
            pgsqlcommand.ExecuteNonQuery();
            }
        }

With this code I can enter the information in the database without problems, getting doubt, and to recover the id that was generated?

below the sql code used to generate the table:

CREATE TABLE public.localpo (
id bigint NOT NULL DEFAULT nextval('localpo_id_seq'::regclass),
nome character varying(255) COLLATE pg_catalog."default",
CONSTRAINT pk_id_localpo PRIMARY KEY (id)
)

2 answers

1

That?

using (var conn = new NpgsqlConnection(conn) {           
    conn.Open();
    using (var cmd = new NpgsqlCommand("INSERT INTO public.localpo(NOME) VALUES (:nome)", conn)) {
        cmd.Parameters.Add(new NpgsqlParameter("nome", "Ricardo Soares"));
        var IdInserido = (int)cmd.ExecuteScalar();
    }
}

I put in the Github for future reference.

  • I added the following code: var Idinserido = (int)pgsqlcommand.Executescalar(); Messagebox.Show(Idinserido.Tostring()); and returned the error: Undefined object reference for an instance of an object.

  • There is another mistake, have to see what did wrong, you gave a code, I showed how to solve the issue with this excerpt, other problems I do not know.

  • The code is exactly what I sent you, and that’s the mistake you’re making

1


There is a command called returning that serves to precisely return your query one of the fields, example based on its string:

INSERT INTO public.localpo(NOME) VALUES ('exemplo') returning id;
  • that’s exactly what was missing

Browser other questions tagged

You are not signed in. Login or sign up in order to post.