Reputation: 453
I'm trying to insert data into a SQL Server CE local database but having an issue I can't solve for the life of me.
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);
}
}
The exception/error I'm getting is
The count of column names and source expressions do not match [Column name count = 3, Source expression count = 1]
I'm unsure if I'm doing this correctly.
Please advise.
Upvotes: 0
Views: 585
Reputation: 25357
You simply misplaced and forgot some single quotes which results in a single string value. Maybe you should rethink how you construct your sql code and use parameters instead:
Try something like this:
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);
Upvotes: 4
Reputation: 550
You doing all in one " ' ' " <-- It thinks its one Column
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
{
}
Upvotes: 0
Reputation: 11763
Try adding a '`' to your variables, so they are 3 distinct ones
player.ID.Replace("/ice/player.htm?id=", null) + "," + player.Name + "," +
player.Team + "')", sql);
in your code above, you have 1 ` to start, and one to end, you need one for each variable
Upvotes: 0
Reputation: 26209
You are inserting single Quote as an extra character as below:
new SqlCeCommand("INSERT INTO Players (PlayerID, PlayerName, Team_Abbreviation) Values ( '" +
player.ID.Replace("/ice/player.htm?id=", null) + "," + player.Name + "," +
player.Team + "')", sql);
should be :
new SqlCeCommand("INSERT INTO Players (PlayerID, PlayerName, Team_Abbreviation) Values(player.ID.Replace("/ice/player.htm?id=", null) + ",'" + player.Name + "','" +
player.Team + "')", sql);
Upvotes: 0