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:
- Create a connection the db NpgsqlConnection con.
- Define my string command “Insert into employee ( employeenum,name,email) VALUES (@empnum, @empname, @email ) returning ID”;
3 .Create a NpgsqlCommand using the command string - Create a NpgSqlParamater defining the data type for each replaceable parameter;
- Call Prepare on the command
When ready to execute
- Set the Value portion of each NpgsqlParamater to the correct value
- Call the appropriate Execute statement ( ExecuteScaler, ExecuteNonQuery, etc)
- 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.