Tuyên bố chuẩn bị .Net Core Npgsql
Sep 09 2020
Tôi đã cố gắng thay đổi một số câu lệnh SQL trong ứng dụng .Net Core để có thể sử dụng lại nhiều hơn bằng cách sử dụng Câu lệnh chuẩn bị nhưng tôi đang gặp sự cố với NpgsqlDbType.
Tôi đã cố gắng làm theo các hướng dẫn tài liệu.
NpgsqlCommand command = new NpgsqlCommand (
" select * from computers where com_phys = @com_phys ",
dbconnection
);
command.Parameters.Add("com_phys", NpgsqlDbType.Varchar);
command.Prepare();
Nhưng nó không được biên dịch, nói rằng
The name 'NpgsqlDbType' does not exist in the current context
Tui bỏ lỡ điều gì vậy? Làm cách nào để sử dụng NpgsqlDbType?
CẬP NHẬT
Tôi chỉ đặt công việc cuối cùng ở đây trong trường hợp nó có thể có lợi cho bất kỳ ai khác
// 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();
Trả lời
2 ESG Sep 09 2020 at 02:16
NpgsqlDbType nằm trong không gian tên NpgsqlTypes. Đảm bảo rằng bạn có NpgsqlTypes đang sử dụng ở trên cùng.
Nếu bạn muốn đặt giá trị đồng thời, hãy sử dụng AddWithValuethay vìAdd
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();
Nếu bạn muốn thêm tham số một lần và thực thi nhiều lần, bạn có thể giữ một tham chiếu đến tham số
var parameter = command.Parameters.Add("com_phys", NpgsqlDbType.Varchar);
// Later, in a loop
parameter.Value = "someValue";