incorrect syntax near 's'. unclosed quotation mark after the character string ')'

一个人想着一个人 提交于 2020-01-04 04:19:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!