3

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 ')'

4

2 回答 2

10

您插入的数据可能包含特殊字符,例如单引号。更改为参数化查询,以便正确转义值。一个很好的例子和解释是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();
于 2012-09-03T08:47:07.343 回答
0

如果字符串的值中有“'”,则该类型的错误即将到来,因此从字符串中删除“'”然后执行查询。

于 2012-09-03T08:47:59.403 回答