我的应用程序是在连接到互联网时在线检索数据的应用程序,但允许用户在离线时查看数据。为此,我让应用程序从在线SQL服务器下载相关信息并将其保存到SQLite DB,以便在计算机未连接到Internet时使用。在我的一个窗口上,我有一个搜索功能,可以找到输入字符串的“注释”。所以首先我写了查询它何时连接到SQL数据库:
SqlConnection conn = new SqlConnection(myconnstring);
await conn.OpenAsync();
string sqlstr = "SELECT * FROM " + Application.Current.Properties["connection"] + "_Notes WHERE Written_ID = @uid AND Content LIKE '%' + @srch + '%' ORDER BY Creation_Time DESC";
SqlCommand cmd = new SqlCommand(sqlstr, conn);
cmd.Parameters.AddWithValue("uid", Convert.ToInt32(Application.Current.Properties["userid"].ToString()));
cmd.Parameters.AddWithValue("srch", searchbox.Text.ToString());
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("Notes");
sda.Fill(dt);
notescontrol.ItemsSource = dt.DefaultView;
conn.Close();
所以这完全符合我的要求。它返回具有该字符串的所有注释。接下来,我为SQLite DB创建了一个字符串(该数据库有一个[Office]列,需要匹配用户的当前列):
SQLiteConnection conn = new SQLiteConnection(mysqliteconnstring);
await conn.OpenAsync();
string sqlstr = "SELECT * FROM Notes WHERE Office = @off AND Written_ID = @uid AND Content LIKE '%' + @srch + '%' ORDER BY Creation_Time DESC";
SQLiteCommand cmd = new SQLiteCommand(sqlstr, conn);
cmd.Parameters.AddWithValue("off", Application.Current.Properties["connection"].ToString());
cmd.Parameters.AddWithValue("uid", Convert.ToInt32(Application.Current.Properties["userid"].ToString()));
cmd.Parameters.AddWithValue("srch", searchbox.Text.ToString());
SQLiteDataAdapter sda = new SQLiteDataAdapter(cmd);
DataTable dt = new DataTable("Notes");
sda.Fill(dt);
notescontrol.ItemsSource = dt.DefaultView;
conn.Close();
我做了自己的研究,但没有发现SQL与SQLite中的like语句有任何差异。那么我哪里出错了?
答案 0 :(得分:2)
According to this answer SQLite中的字符串连接运算符为||
。所以你需要两个不同的查询文本。但是,如果更改传递LIKE条件参数的方式
string sqlstr = @"SELECT * FROM Notes WHERE Office = @off
AND Written_ID = @uid
AND Content LIKE @srch
ORDER BY Creation_Time DESC";
....
cmd.Parameters.AddWithValue("@srch", "%" + searchbox.Text + "%");
顺便说一句,searchbox.Text属性已经是一个字符串,不需要在其上调用ToString()。