虚警:SqlCommand,SqlParameter和单引号

时间:2009-05-19 10:30:20

标签: .net c++ sql-server managed-c++

我正在尝试修复代码中的单引号错误:

std::string Index;

connection->Open();
String^ sTableName = gcnew String(TableName.c_str());
String^ insertstring = String::Format("INSERT INTO {0} (idx, rec, date) VALUES (@idx,    @rec, getdate())", sTableName);
SqlCommand^ command = gcnew SqlCommand(insertstring, connection);
String^ idx = gcnew String(Index.c_str());
command->Parameters->Add("@idx", SqlDbType::VarChar)->Value = idx;

错误是如果idx =“that”,则SQL无法说出语法错误。显然,问题在于引用。 但是一些谷歌搜索显示使用参数是使用引号的方式。如果type是TEXT而不是VARCHAR,那么SqlParameter运行良好。

除了手动加倍字符串中的引号符号数量之外,还有其他解决方案吗?

更新:我尝试在SQL Management Studio中手动编辑此字段,但它不允许在VARCHAR字段中使用单引号。这在SQL中是正常的吗?

4 个答案:

答案 0 :(得分:2)

我怀疑问题是你的表名中的引号,或者idx听起来更像是数字类型的名称而不是字符类型。


根据您的更新,我建议您检查管理工作室中表格的额外限制。

答案 1 :(得分:1)

老实说,我从未遇到过SqlParameters的问题。但请尝试以下方法:

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue.aspx

command->Parameters->AddWithValue("@idx", idx);

这应该可以正常工作并为您编码。

答案 2 :(得分:0)

如果你确定它是一个引号概率那么,

C#代码:

idx = idx.Replace("'", "''"); 

可以解决问题。

答案 3 :(得分:0)

对不起。

问题出在SQL触发器的代码中。删除后,一切正常。