我试图通过认为开发人员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