我試圖通過認爲開發人員API的遊戲的數據匹配並將它們存儲在數據庫中。我如何將x.something傳遞給我的數據庫。當我嘗試這樣的事:通過MySql傳遞Foreach變量插入
using (var web = new WebClient())
{
web.Encoding = System.Text.Encoding.UTF8;
var jsonString = responseFromServer;
var jss = new JavaScriptSerializer();
var MatchesList = jss.Deserialize<List<Matches>>(jsonString);
string connectString = "Server=myServer;Database=myDB;Uid=myUser;Pwd=myPass;";
MySqlConnection connect = new MySqlConnection(connectString);
MySqlCommand command = connect.CreateCommand();
command.CommandText = "INSERT into data (level, name) values('" + x.Account_Level + "','" + x.Name + "')";
string MatchesListStr = "";
connect.Open();
foreach (Matches x in MatchesList)
{
MatchesListStr = MatchesListStr + ", " + x.Name + ", " + x.Account_Level + ", " + x.Reference_Name + "!";
command.ExecuteNonQuery();
}
connect.Close();
MessageBox.Show(MatchesListStr);
}
它說:
型 'MySql.Data.MySqlClient.MySqlException' 未處理的異常發生在MySql.Data.dll
附加信息:您的SQL語法有錯誤;檢查 對應於您的MySQL服務器版本的權利 語法使用近「字的手冊,
任何幫助表示讚賞,我是新來的C#。謝謝!
編輯 - 更新的代碼:
using (var web = new WebClient())
{
web.Encoding = System.Text.Encoding.UTF8;
var jsonString = responseFromServer;
var jss = new JavaScriptSerializer();
var MatchesList = jss.Deserialize<List<Matches>>(jsonString);
string connectString = "Server=myServer;Database=myDB;Uid=myUser;Pwd=myPass;";
MySqlConnection connect = new MySqlConnection(connectString);
MySqlCommand command = connect.CreateCommand();
connect.Open();
foreach (Matches x in MatchesList)
{
command.CommandText = "INSERT into data (level, mode) values(@level, @mode)";
command.Parameters.AddWithValue("@level", x.Account_Level);
command.Parameters.AddWithValue("@mode", x.Name);
command.ExecuteNonQuery();
}
connect.Close();
}
public class Matches
{
public int Account_Level { get; set; }
public string Name { get; set; }
}
用相同的答案之前回復。
我會看看使用[準備語句](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.prepare(v = vs.110).aspx)來使確保字符正確轉義。如果你在x.Account_Level或x.Name變量中有奇怪的字符,它將導致無效的SQL。 – zerodiff 2014-08-27 21:35:34
我在文檔中寫下了所有這些。我沒有包括它,因爲我認爲這是一個給定的因素。 – Kragalon 2014-08-27 23:05:56