Dichiarazione preparata di .Net Core Npgsql
Ho provato a modificare alcune istruzioni SQL in un'app .Net Core per essere più riutilizzabili utilizzando le istruzioni preparate, ma ho problemi con NpgsqlDbType.
Ho provato a seguire le istruzioni della documentazione.
NpgsqlCommand command = new NpgsqlCommand (
" select * from computers where com_phys = @com_phys ",
dbconnection
);
command.Parameters.Add("com_phys", NpgsqlDbType.Varchar);
command.Prepare();
Ma non riesce a compilare, dicendo
The name 'NpgsqlDbType' does not exist in the current context
Mi sto perdendo qualcosa? Come si usa NpgsqlDbType?
AGGIORNARE
Sto solo mettendo qui l'ultima cosa funzionante nel caso possa giovare a qualcun altro
// prepare
NpgsqlCommand command = new NpgsqlCommand (
" select * from computers where com_phys = @com_phys ",
dbconnection
);
var param01 = command.Parameters.Add("com_phys", NpgsqlDbType.Varchar);
command.Prepare();
// execute 01
param01.Value = "value01";
var results = command.ExecuteReader();
while(results.Read()) {
// nothing
}
command.Close();
// execute 02
param01.Value = "value02";
var results = command.ExecuteReader();
while(results.Read()) {
// nothing
}
command.Close();
Risposte
NpgsqlDbType si trova nello spazio dei nomi NpgsqlTypes. Assicurati di avere un NpgsqlTypes in uso nella parte superiore.
Se si desidera impostare il valore contemporaneamente, utilizzare AddWithValueinvece diAdd
NpgsqlCommand command = new NpgsqlCommand (
" select * from computers where com_phys = @com_phys ",
dbconnection
);
command.Parameters.AddValue("com_phys", NpgsqlDbType.Varchar, value);
// OR command.Parameters.AddValue("com_phys", NpgsqlDbType.Varchar, size, value);
// OR command.Parameters.AddValue("com_phys", value);
command.Prepare();
Se si desidera aggiungere il parametro una volta ed eseguire più volte, è possibile mantenere un riferimento al parametro
var parameter = command.Parameters.Add("com_phys", NpgsqlDbType.Varchar);
// Later, in a loop
parameter.Value = "someValue";