c# - 's' 附近的语法不正确。字符串 ')'后的引号不闭合

标签 c# visual-studio-2010 sql-server-2008

我在编程方面有点菜鸟,我想知道我在这里做错了什么 - 有人可以帮助我吗?

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

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

我得到以下异常:

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

最佳答案

您要插入的数据可能包含单引号等特殊字符。更改为参数化查询,以便正确转义值。一个很好的例子和解释是 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();

关于c# - 's' 附近的语法不正确。字符串 ')'后的引号不闭合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12244540/

相关文章:

sql-server - 如何在不丢失数据的情况下更改SQL Server数据库中的列数据类型?

python - 如何在 Python 中使用表值参数访问 SQL Server 2008 存储过程

C# 面板列表

c++ - 让 VS10 调试器跳转某些库有问题吗?

sql - 不使用 SMO 将登录名和用户添加到 SQL Server

c++ - 如何断言给定的编译器选项设置为给定的值 VS2010?

c# - 如何通过正则表达式屏蔽输入? 1112223333 或 1112223333444

c# - 将文件扩展名与应用程序相关联

c# - 在 c# winforms 中的窗体之间传递数据的最安全方法

c# - 如何格式化 DateTime 变量以获取月份,然后将值放入 C# 中的字符串? [VS2005]