npgsql

I see two approaches to npgsql prepares. Trying to understand the differences


I have been exploring how to access Postgres from C#. When using prepared statements ( which I almost always want to do) the website recommends the following:

  1. Create a connection the db NpgsqlConnection con.
  2. Define my string command "Insert into employee ( employeenum,name,email) VALUES (@empnum, @empname, @email ) returning ID"; 3 .Create a NpgsqlCommand using the command string
  3. Create a NpgSqlParamater defining the data type for each replaceable parameter;
  4. Call Prepare on the command

When ready to execute

  1. Set the Value portion of each NpgsqlParamater to the correct value
  2. Call the appropriate Execute statement ( ExecuteScaler, ExecuteNonQuery, etc)
  3. Deal with the reply

It occurred to me that I could simply choose to use SQL syntax when preparing, IE

1 Create a connection to the db NpgsqlConneciton con 2. Define my string command "PREPARE insertemployee ( varchar, varchar, varchar) AS INSERT into Employee ( employeenum, name, email) VALUES ($1, $2, $3 ) RETURNING ID""; 3, Create a NpgSQL command using the command string. 4. Execute the command

When ready to execute I would 1 Create a command string with the appropriate parameters IE "Execute insertemployee('', 'value2', 'value3') 2.Create a NpgsqlCommand with that command string 3 Execute the command and deal with the reply.

My questions: If the first method is preferred, why is it better than the second method? If I were to look at the commands sent over the wire to the server, would they be substantially different?

Thanks.


Solution

  • Using NpgsqlCommand.Prepare() is slightly more efficient, as you can retain a reference to an NpgsqlCommand and reexecute it with different parameters. If you create an NpgsqlCommand each time for EXECUTE, there's a bit more overhead there.

    But in practice, the difference should be negligible for almost all applications and it wouldn't matter.