.Net Core Npgsql Prepared Statement
Próbowałem zmienić niektóre instrukcje SQL w aplikacji .Net Core, aby były one bardziej wielokrotnego użytku, używając instrukcji przygotowanych, ale mam problem z typem NpgsqlDbType.
Próbowałem postępować zgodnie z instrukcjami dokumentacji.
NpgsqlCommand command = new NpgsqlCommand (
" select * from computers where com_phys = @com_phys ",
dbconnection
);
command.Parameters.Add("com_phys", NpgsqlDbType.Varchar);
command.Prepare();
Ale nie można się skompilować, mówiąc
The name 'NpgsqlDbType' does not exist in the current context
Czy coś mi brakuje? Jak używać NpgsqlDbType?
AKTUALIZACJA
Umieszczam tutaj ostatnią działającą rzecz, na wypadek gdyby przyniosła korzyści komukolwiek innemu
// 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();
Odpowiedzi
NpgsqlDbType znajduje się w przestrzeni nazw NpgsqlTypes. Upewnij się, że u góry znajduje się opcja using NpgsqlTypes.
Jeśli chcesz ustawić wartość w tym samym czasie, użyj AddWithValuezamiastAdd
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();
Jeśli chcesz dodać parametr raz i wykonać go wiele razy, możesz zachować odniesienie do parametru
var parameter = command.Parameters.Add("com_phys", NpgsqlDbType.Varchar);
// Later, in a loop
parameter.Value = "someValue";