我一直在尝试通过使用Prepared Statements来更改.Net Core应用程序中的某些SQL语句,以使其更可重用,但我在使用NpgsqlDbType时遇到了麻烦。
我试图按照文档说明进行操作。
NpgsqlCommand command = new NpgsqlCommand (
" select * from computers where com_phys = @com_phys ",
dbconnection
);
command.Parameters.Add("com_phys", NpgsqlDbType.Varchar);
command.Prepare();
但它无法编译,说
The name 'NpgsqlDbType' does not exist in the current context
我想念什么吗?如何使用NpgsqlDbType?
更新
我只是把最后的工作放在这里,以防它可以使其他任何人受益
// 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();
NpgsqlDbType在NpgsqlTypes命名空间中。确保在顶部使用NpgsqlTypes。
如果要同时设置值,请使用AddWithValue
代替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();
如果要一次添加参数并多次执行,则可以保留对该参数的引用
var parameter = command.Parameters.Add("com_phys", NpgsqlDbType.Varchar);
// Later, in a loop
parameter.Value = "someValue";
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句