我正在尝试通过开发人员 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);
}
它说:
An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
Additional information: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '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; }
}
回复与之前相同的答案。
最佳答案
您当前的方法容易受到 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
)。这就是为什么在命名变量时应该更加小心。
关于c# - 通过 MySql Insert 传递 Foreach 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25537036/