首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >.Net Core准备语句

.Net Core准备语句
EN

Stack Overflow用户
提问于 2020-09-08 18:41:14
回答 1查看 235关注 0票数 2

我一直试图通过使用准备好的语句来更改.Net核心应用程序中的一些SQL语句,以提高可重用性,但我在使用NpgsqlDbType时遇到了麻烦。

我试着按照文件说明来做。

代码语言:javascript
复制
NpgsqlCommand command = new NpgsqlCommand (
    " select * from computers where com_phys = @com_phys ",
    dbconnection
);
command.Parameters.Add("com_phys", NpgsqlDbType.Varchar);
command.Prepare();

但是它没有编译,说

代码语言:javascript
复制
The name 'NpgsqlDbType' does not exist in the current context

我是不是遗漏了什么?如何使用NpgsqlDbType?

更新

我只是把最后的工作放在这里,以防其他人从中受益

代码语言:javascript
复制
// 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();
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-08 19:16:26

NpgsqlDbType位于NpgsqlTypes命名空间中。确保顶部有一个正在使用的NpgsqlTypes。

如果要同时设置值,请使用AddWithValue而不是Add

代码语言:javascript
复制
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();

如果要添加参数一次并多次执行,则可以保留对参数的引用。

代码语言:javascript
复制
var parameter = command.Parameters.Add("com_phys", NpgsqlDbType.Varchar);

// Later, in a loop
parameter.Value = "someValue";
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63799827

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档