2010-11-28 78 views
1

試圖從MySql數據庫執行select語句。下面的作品,當我插上直接變量:C#MySql語句。發現我的錯誤!

MySqlCommand playerSearch = conn.CreateCommand(); 
playerSearch.CommandText = @"select username from players where username like '%" + username + "%'"; 
playerSearch.Prepare(); 
// Execute the command, get the restuls, etc. 

但是如果我試圖用paramater將做到這一點的首選方式,如:

MySqlCommand playerSearch = conn.CreateCommand(); 
playerSearch.CommandText = @"select username from players where username like @username"; 
playerSearch.Prepare(); 
playerSearch.Parameters.AddWtihValue("@username", "'%" + username + "%'"); 
// Execute the command, get the restuls, etc. 

我沒有得到任何結果從查詢回來。到目前爲止,我還沒有想出爲什麼這不起作用。有什麼建議?

回答

6

刪除內部引號。

playerSearch.Parameters.AddWtihValue("@username", "%" + username + "%"); 
+0

工作就像一個魅力,謝謝。猜測這是由於AddWithValue的情況? – vimalloc 2010-11-28 21:47:25

-1

那麼,只需運行Mysql並直接輸入查詢,比mysql服務器會給你的信息,如果你的語法錯誤是,如果有的話。 最好的方法是,讓程序以純文本(我的意思是在運行時)顯示您的查詢,然後將它放到mysql命令行中。

1

構建通配符到查詢,而不是數據:

MySqlCommand playerSearch = conn.CreateCommand(); 
playerSearch.CommandText = @"select username from players where username like '%' + @username + '%'"; 
playerSearch.Prepare(); 
playerSearch.Parameters.AddWtihValue("@username", username); 
// Execute the command, get the restuls, etc. 

更妙的是,完全避免寫這有點像查詢。查詢中的初始通配符會阻止數據庫使用任何索引。使用真正的full-text search機制。 LIKE是一個可憐的替代品。