2011-11-03 81 views
0

我有一個函數,應該採取x2字符串輸入並將它們插入到mySQL數據庫中。這兩個字符串是查詢結果,可以是任何東西。測試過程中出現此錯誤。INSERT錯誤 - 1064

前{「您的SQL語法錯誤;檢查手冊中 對應於你的MySQL服務器版本正確的語法使用 附近是一個很好的開始,但是我可以向你保證它贏得」 T爲他沒有按」 位於第1" 行} {System.Exception的} MySql.Data.MySqlClient.MySqlException

一些想法我來了以後,它的錯誤,因爲我的一個字符串包含撇號結論'字符,並與mySQL語法混淆。我可以對我的字符串做些什麼,以確保它們可以像所有字符一樣插入到我的表中?

我試過使用AddWithValue()函數進行字符串操作&,但目前爲止都沒有工作。我認爲使用Replace函數會有幫助,但我很喜歡什麼是我希望輸出的正確的mySQL語法。

任何想法/建議讚賞。謝謝。

public void Insert(string SearchQuery, string QueryResult) 
     { 
      const string connString = "SERVER=localhost; DATABASE=social_db; UID=root; PASSWORD=pass;"; 
      MySqlConnection connection = new MySqlConnection(connString); 
      MySqlCommand command = connection.CreateCommand(); 

      QueryResult = QueryResult.Replace("'", "\'"); 

      command.CommandText = 
       "INSERT INTO social_tbl (SearchQuery, QueryResult)" 
       + " VALUES " 
       + "('" + SearchQuery + "', '" + QueryResult + "');"; 

      //command.CommandText = 
      //"INSERT INTO social_tbl (SearchQuery, QueryResult) VALUES ('@SearchQuery', '@QueryResult');"; 

      //command.Parameters.AddWithValue("@SearchQuery", SearchQuery); 
      //command.Parameters.AddWithValue("@QueryResult", QueryResult); 

      connection.Open(); 

      command.ExecuteNonQuery(); 

      connection.Close();   
     } 

回答

0

試試這個:

INSERT INTO social_tbl ('SearchQuery', 'QueryResult') 
1

從不將參數轉換成一個SQL字符串 - this opens up a very serious security hole (SQL injection!)

使用

 command.CommandText = 
     "INSERT INTO social_tbl (SearchQuery, QueryResult) VALUES (@SearchQuery, @QueryResult);"; 

     command.Parameters.AddWithValue("@SearchQuery", SearchQuery); 
     command.Parameters.AddWithValue("@QueryResult", QueryResult); 

有了這個,你不需要Replace並使用「綁定參數」,它讓你從SQL注入安全的,有時甚至是利益的表現。在你原來的代碼中,每個參數都有'--當使用「綁定參數」時,這不是必需的,它不會起作用(正如你已經發現的那樣)。

+0

這有助於消除我的錯誤,但是這會將NULL值插入到我的數據表中。 SearchQuery&QueryResult的DataType只是Text,如果我傳遞的字符串太大,我該怎麼做/在這裏使用? – Draznar

+0

@Draznar你應該總是檢查傳入的數據,如果它太大,你可以拋出一個異常和/或更改數據庫列的寬度和/或根據您的要求適當縮短參數... – Yahia

+0

@Draznar please don'噸忘記upvote和/或「標記爲接受」任何答案是有幫助的... – Yahia

0

我不完全確定爲什麼,但在查看了一些其他問題以瞭解洞察之後,我發現使用'?'而不是'@'字符。似乎解決了我的問題。

command.CommandText = 
      "INSERT INTO socialm_tbl (SearchQuery, QueryResult) VALUES (?SearchQuery, ?QueryResult);"; 

      command.Parameters.AddWithValue("?SearchQuery", SearchQuery); 
      command.Parameters.AddWithValue("?QueryResult", QueryResult);