问题
I am kinda noob in programming, and I was wondering what I have done wrong here - can some one help me out?
I am making a console app in which it syncs two databases, but when I try to insert the data into the table it throws this exception; The code is:
public static void AddInterationPath(SqlConnection conDS_ReleaseCri, DataRow dr)
{
SqlCommand insertNewAreaPath = new SqlCommand("INSERT INTO InterationPath (ID,NodePath) VALUES(" + dr[0].ToString() + ",'" + dr[2].ToString() + "')", conDS_ReleaseCriterions);
insertNewAreaPath.ExecuteNonQuery();
}
public static void AddAreaPath(SqlConnection conDS_ReleaseCri, DataRow dr)
{
SqlCommand insertNewAreaPath = new SqlCommand("INSERT INTO AreaPath (ID,NodePath) VALUES(" + dr[0].ToString() + ",'" + dr[2].ToString() + "')", conDS_ReleaseCriterions);
insertNewAreaPath.ExecuteNonQuery();
}
And I get the following exception:
incorrect syntax near 's'. unclosed quotation mark after the character string ')'
回答1:
The data you are inserting probably contains special characters like single quotes. Change to a parameterized query so the values are escaped properly. A good example and explanation is http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html.
[Edit: Added an example. ]
For example, replace the contents of your first function with:
SqlCommand insertNewAreaPath = new SqlCommand(
"INSERT INTO InterationPath (ID, NodePath) VALUES(@ID, @NodePath)",
conDS_ReleaseCriterions);
insertNewAreaPath.Parameters.Add("@ID", dr[0]);
insertNewAreaPath.Parameters.Add("@NodePath", dr[2]);
insertNewAreaPath.ExecuteNonQuery();
回答2:
If you have "'" inside of value of string then that type's of error is comming, So remove "'" from string then execute query.
来源:https://stackoverflow.com/questions/12244540/incorrect-syntax-near-s-unclosed-quotation-mark-after-the-character-string