c# - 尝试在 C# Winform 中查询 PostgreSQL 数据库时,ExecuteReader 上出现 Npgsql.PostgresException 错误
问题描述
我正在尝试从数据库查询中获取字符串列表并将其放入 ComboBox 中。
我尝试执行此操作的代码以DataGridVew
Cell Click 事件中的 from 以下内容开头:
// Bind combobox to dgv and than add list of New Values to combobox
DataGridViewComboBoxCell cboNewValueList = new DataGridViewComboBoxCell();
// Get fields to build New Value query
List<string> lsNewValuesResult = new List<string>();
string strCategory = dtCategories.Rows[e.RowIndex][1].ToString();
string strCompanyName = cboSelectCompany.Text;
string strQueryGetNewValuesValidationInfo = "SELECT validationdb, validationtable, validationfield, validationfield2, validationvalue2" +
" FROM masterfiles.categories" +
" WHERE category = @category";
// Pass validation info query to db class and return list of New Values
db getListOfNewValues = new db();
lsNewValuesResult = getListOfNewValues.GetNewValuesList(strQueryGetNewValuesValidationInfo, strCategory, strCompanyName);
//Populate the combobox with the list of New Values
foreach (string strListItem in lsNewValuesResult)
{
cboNewValueList.Items.Add(strListItem);
}
我需要使用上面的查询来找出填充查询需要哪些表和字段lsNewValuesResult
。
在GetNewValuesList
我有这个代码:
public List<string> GetNewValuesList(string strValidationInfoQuery, string strCategory, string strCompanyName)
{
List<string> lsValidationInfo = new List<string>();
List<string> lsNewValuesList = new List<string>();
using (NpgsqlConnection conn = new NpgsqlConnection(connString))
using (NpgsqlCommand cmd = new NpgsqlCommand(strValidationInfoQuery, conn))
{
cmd.Parameters.Add(new NpgsqlParameter("@cateogry", strCategory));
conn.Open();
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
int intReaderIndex;
for (intReaderIndex = 0; intReaderIndex <= reader.FieldCount - 1; intReaderIndex++)
{
// reader indexes 3 & 4 correspond to categories.validationfield2 and validationvalue2, which can be null
if (string.IsNullOrEmpty(reader[intReaderIndex].ToString()))
{
lsValidationInfo.Add("");
}
else
{
lsValidationInfo.Add(reader.GetString(intReaderIndex));
}
Console.WriteLine("reader index " + intReaderIndex + ": " + reader.GetString(intReaderIndex));
}
}
}
}
// Use the items in lsValidationInfo to build the query to get the New Values
}
就ExecuteReader()
行了,虽然我得到一个 Npgsql.PostgresException,但“操作符不存在:@ 字符变化”。
让我感到困惑的是,我在同一个项目中成功完成同样事情的另一个代码块之后对此进行了建模。这几乎是复制/粘贴,然后更改新函数的参数和对象名称。
解决方案
所以我认为问题出在以下行:
cmd.Parameters.Add(new NpgsqlParameter("@cateogry", strCategory));
尝试替换为以下内容:
cmd.Parameters.AddWithValue("category", strCategory);
推荐阅读
- algorithm - 最小化数组的“成本”
- java - 使用Java中的sql查询结果将数据加载到组合对象中
- python - 错误消息:“未压缩的距离矩阵”
- angular - Angular:在构造函数中声明并分配依赖项的属性
- security - 使用无密码 root ssh 的 Redhat 自动化操作
- python - python中replace()的用户定义函数?
- git - Rebase 分支保留基于它的另一个分支上的提交
- javascript - ExtJS 从多个代理源填充存储
- asp.net-core - Visual Studio 2019 .NET Core 3 gRpc 不生成服务文件
- html - 如何让两种不同的东西并存?