在寫使用access數據庫的c#程序過程中,遇到各種莫名奇妙的問題。例如使用"like"進行模糊查詢,在access查詢視圖中要使用"*"做模糊匹配(sql中是"%").
原以為在程序中的查詢字符串也應該使用"*",事實上並非如此!
在access數據庫中調試用"*",程序中要改過來用"%",否則是查詢不到任何數據的,而且vs還不報任何錯,調試都找不到原因。
try { _strSql=""; if (dataGridView1.Rows.Count <= 1) { if (dataGridView1.Rows[0].Cells[0].Value == null || dataGridView1.Rows[0].Cells[1].Value == null || dataGridView1.Rows[0].Cells[2].Value == null) { return; } else { string filed = GetArrayElement(Cxzd, dataGridView1.Rows[0].Cells[0].Value.ToString().Trim(), 1); //string type = GetArrayElement(Cxzd, filed, 2); string cs = Cxfs[dataGridView1.Rows[0].Cells[1].Value.ToString().Trim()].ToString(); string content = dataGridView1.Rows[0].Cells[2].Value.ToString(); if (cs == "like") { content = "'%" + content + "%'"; } _strSql = string.Format("where {0} {1} {2} ", filed, cs, content); } }
后來查資料,原來是連接access驅動程序的問題,由於我的程序中連Access用的是oledb驅動程序,所以在這里 不能用“*”,必須用“%”。如果用的是DAO訪問Access數據庫,則必須用“*”。