我试图将数据插入到SQL Server CE本地数据库中,但是遇到了我无法解决的问题。
foreach (var player in cells)
{
var sql = new SqlCeConnection(
@"Data Source=H:\Repositories\NHL-Connected\NHLConnected\NHLScraper\app.sdf");
try
{
sql.Open();
var cmd =
new SqlCeCommand("INSERT INTO Players (PlayerID, PlayerName, Team_Abbreviation) Values ( '" +
player.ID.Replace("/ice/player.htm?id=", null) + "," + player.Name + "," +
player.Team + "')", sql);
int affectedRows = cmd.ExecuteNonQuery();
if (affectedRows > 0) Console.WriteLine("Successful.");
else Console.WriteLine("Failed.");
}
catch (SqlCeException ex)
{
Console.WriteLine(ex.Message);
}
}
我得到的例外/错误是
列名和源表达式的计数与[Column]不匹配 name count = 3,Source expression count = 1]
我不确定我是否正确地这样做了。
请告知。
答案 0 :(得分:4)
你只是放错地方并忘记了一些单引号,这会导致单个字符串值。也许你应该重新思考如何构造你的sql代码并改用参数:
尝试这样的事情:
var cmd = new SqlCeCommand(
"INSERT INTO Players (PlayerID, PlayerName, Team_Abbreviation) VALUES (@ID, @Name, @Team);", sql);
cmd.Parameters.AddWithValue("@ID", player.ID.Replace("/ice/player.htm?id=", null));
cmd.Parameters.AddWithValue("@Name", player.Name);
cmd.Parameters.AddWithValue("@Team", player.Team);
答案 1 :(得分:0)
你在一个“''”中做所有事情< - 它认为它是一个列
try
{
var cmd = new SqlCeCommand("INSERT INTO Players (PlayerID, PlayerName, Team_Abbreviation) Values (@PlayerID,@PlayerName,@Team_Abbreviation)", sql);
cmd.Parameters.AddWithValue("@PlayerID", PlayerIDTxt);
cmd.Parameters.AddWithValue("@PlayerName", PlayerNameTxt);
cmd.Parameters.AddWithValue("@Team_Abbreviation", Team_AbbreviationTxt);
cmd.Open();
int affectedRows = cmd.ExecuteNonQuery();
cmd.Close();
}
catch
{
}
答案 2 :(得分:0)
尝试在变量中添加“`”,因此它们是3个不同的变量
player.ID.Replace("/ice/player.htm?id=", null) + "," + player.Name + "," +
player.Team + "')", sql);
在你上面的代码中,你有1个开始,一个结束,每个变量需要一个