2012-06-20 47 views
3

我得到:C#MySQL的語法錯誤

您的SQL語法錯誤;檢查對應於你的MySQL服務器 版本正確的語法使用近'譜」 WHERE規範ID = 42' 在行1

雖然運行該代碼的手冊:

public System.Drawing.Image GetImage(int index) 
{ 
using (MySqlCommand command = connection.CreateCommand()) 
{ 
    //command.CommandText = "SELECT imageObj FROM spectra WHERE specId=42"; <== Works OK! 

    command.CommandText = "SELECT imageObj FROM @tname WHERE [email protected]"; 
    command.Parameters.AddWithValue("@index", index); 
    command.Parameters.AddWithValue("@tname", "spectra"); 

    using (MySqlDataReader reader = command.ExecuteReader()) 
    { 
    if (reader.Read()) 
    { 
    return (System.Drawing.Image)Serial.ByteArrayToObject((byte[])reader[0]); 
    } 
    } 
} 
return null; 
} 

我覺得問題是光譜附近的報價。我怎樣才能刪除它們?

+0

請記住,你不能投了'byte'到'的byte []'... –

+0

無關。功能正常工作時的語法就可以了。 – Igor

回答

4

不能用參數替換表名。可悲的是,這只是不被支持。只有WHERE子句中的參數值可以用這種方式替換。

您必須自己進行替換,而不是依靠MySqlCommand對象。像這樣的東西應該工作:

string tableName = "spectra"; 
command.CommandText = 
    String.Format("SELECT imageObj FROM {0} WHERE [email protected]", tableName); 
command.Parameters.AddWithValue("@index", index); 
+0

現在正常工作..感謝您的快速響應。 – Igor