我正在写一个使用SQLite和C#的WinForms数据库应用程序。我有一个失败的sqlite查询,并且我不确定哪里出错,因为我尝试了所有我能想到的。看看我的C#SQLite查询,我做错了什么?
public DataTable searchSubs(String businessName, String contactName)
{
string SQL = null;
if ((businessName != null && businessName != "") && (contactName != null && contactName != ""))
{
// provided business name and contact name for search
SQL = "SELECT * FROM SUBCONTRACTOR WHERE BusinessName LIKE %@BusinessName% AND Contact LIKE %@ContactName%";
}
else if ((businessName != null && businessName != "") && (contactName == null || contactName == ""))
{
// provided business name only for search
SQL = "SELECT * FROM SUBCONTRACTOR WHERE BusinessName LIKE %@BusinessName%";
}
else if ((businessName == null || businessName == "") && (contactName != null && contactName != ""))
{
// provided contact name only for search
SQL = "SELECT * FROM SUBCONTRACTOR WHERE Contact LIKE %@ContactName%";
}
else if ((businessName == null || businessName == "") && (contactName == null || contactName == ""))
{
// provided no search information
SQL = "SELECT * FROM SUBCONTRACTOR";
}
SQLiteCommand cmd = new SQLiteCommand(SQL);
cmd.Parameters.AddWithValue("@BusinessName", businessName);
cmd.Parameters.AddWithValue("@ContactName", contactName);
cmd.Connection = connection;
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
da.Fill(ds);
DataTable dt = ds.Tables[0];
return dt;
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
return null;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
我不断得到一个错误,说它在%附近失败。这一切都很好,但我认为我错了,但我不知道在哪里!我尝试添加围绕“喜欢”变量单引号,像这样:
SQL = "SELECT * FROM SUBCONTRACTOR WHERE Contact LIKE '%@ContactName%'";
,并坦白地说,这是所有我能想到的。有人有主意吗?
值。 IsNullOrEmpty()'而不是单独的比较到'null'和'“”' – juharr 2011-01-05 02:36:15
@juharr:好的一点,我会改变他们。谢谢! – CODe 2011-01-05 02:42:11
“返回没有记录”不会给应答者带来任何有用的信息。你可以在'cmd'执行时设置断点,并检查sql查询字符串和参数a重新正确。 – 2011-01-05 02:54:30