查看我的C#SQLite查询,我做错了什么?

时间:2011-01-05 02:23:30

标签: c# winforms sqlite

我正在使用SQLite和C#编写WinForms数据库应用程序。我有一个失败的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();
        }
    }

我不断得到一个错误,说它在%s附近失败了。这一切都很好,花花公子,但我想我的构造错了,但我不知道在哪里!我尝试在“喜欢”变量周围添加撇号,如下所示:

SQL = "SELECT * FROM SUBCONTRACTOR WHERE Contact LIKE '%@ContactName%'";

老实说,这就是我能想到的。有人有什么想法吗?

1 个答案:

答案 0 :(得分:2)

因为您使用的是参数值,所以不需要'%'。所以你应该有像

这样的东西

SQL = "SELECT * FROM SUBCONTRACTOR WHERE Contact LIKE @ContactName“;

需要将'%'添加到传递给参数

的值中

var contactNameSearch = string.Format("{0}%", contactName);
cmd.Parameters.AddWithValue("@ContactName", contactNameSearch);