‘s’附近的语法不正确。 字符串后的未闭合引号’)’

我在编程方面有点不错,而且我想知道我在这里做错了什么 – 有人可以帮助我吗?

我正在制作一个控制台应用程序,它同步两个数据库,但当我尝试将数据插入表中时,它会抛出此exception; 代码是:

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(); } 

我得到以下exception:

‘s’附近的语法不正确。 字符串后的未闭合引号’)’

您插入的数据可能包含特殊字符,如单引号。 更改为参数化查询,以便正确转义值。 一个很好的例子和解释是http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html 。

[编辑:添加了一个示例。 ]

例如,用以下内容替换第一个函数的内容:

 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(); 

如果你在字符串值中有“’”,那么该类型的错误就会出现,所以从字符串中删除“’”然后执行查询。