是否有任何正确的方法从某个特定字符串值搜索的OLEDB连接中检索数据



我想使用此查询从SQL Server检索一个类别。我在数据库中有数据,此查询在SQL Server中运行良好。但当我将它与oledb命令一起使用时,它不会从服务器返回任何数据。怎么了?

public Category GetCategoryByCategoryName(string categoryName)
{
Category _category = null;
using (OleDbConnection con = new OleDbConnection(_connectionString))
{
string sql = "select * from Categories where CategoryName=?";
OleDbCommand cmd = new OleDbCommand(sql, con);
cmd.Parameters.AddWithValue("@cName", categoryName);
try
{
con.Open();
OleDbDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
_category.Id = Convert.ToInt32(rdr["Id"]);
_category.CategoryName = rdr["CategoryName"].ToString();
}
rdr.Close();
}
}
catch (Exception ex)
{
_category = null;
}
}
return _category;
}

我不知道"正确",但一个"好"的方法可能是安装Dapper并将代码简化为:

public Category GetCategoryByCategoryName(string categoryName)
{
using (OleDbConnection con = new OleDbConnection(_connectionString))
{
return con.QueryFirstOrDefault<Category>(
"select * from Categories where CategoryName=?cn?",
new { cn = categoryName }
);
}
}

参考文献:使用OleDb 在Dapper中传递查询参数

它应该:Category _category = new Category();而不是:Category _category = null;

最新更新