我正在尝试通过考虑开发人员API的游戏的数据匹配并将其存储在数据库中。我如何将x.something传递到我的数据库。当我尝试这样的事情时:
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服务器版本对应的手册 在'character,
附近使用的语法
感谢任何帮助,我是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; }
}
回答与之前相同的答案。
答案 0 :(得分:1)
您当前的方法易受SQL injection影响。您应该通过parameterising查询来避免这种情况。
我希望您遇到问题,因为当您提供字符串时,表中的level
列将整数作为输入。
我会做这样的事情来解决你的问题:
command.CommandText = "INSERT into data (level, name) values (@level, @name)";
// Now let’s add the parameters themselves.
command.Parameters.AddWithValue("@level", x.level);
command.Parameters.AddWithValue("@name", x.name);
注意:我还假设您正在向例程提供名为x
的参数(类型为Matches
)。这就是为什么在命名变量时应该更加小心。