如何解决.Net Core Npgsql预准备语句
我一直在尝试通过使用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",size,value);
command.Prepare();
如果要一次添加参数并多次执行,可以保留对该参数的引用
var parameter = command.Parameters.Add("com_phys",NpgsqlDbType.Varchar);
// Later,in a loop
parameter.Value = "someValue";
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。