Reputation: 63
I wanted to retrieve a Category from SQL Server using this query. I have data in the database and this query worked well in SQL Server. But when I use it with oledb command, it does not return any data from the server. What's the problem?
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;
}
Upvotes: 0
Views: 906
Reputation: 63
It should:
Category _category = new Category();
instead of:
Category _category = null;
Upvotes: 1
Reputation: 74605
I don't know about "proper" but a "good" way might be to install Dapper and reduce your code to:
public Category GetCategoryByCategoryName(string categoryName)
{
using (OleDbConnection con = new OleDbConnection(_connectionString))
{
return con.QueryFirstOrDefault<Category>(
"select * from Categories where CategoryName=?cn?",
new { cn = categoryName }
);
}
}
References: Passing query parameters in Dapper using OleDb
Upvotes: 1