误报:SqlCommand、SqlParameter 和单引号
我正在尝试修复代码中的单引号错误:
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's”,则 SQL 失败,表示存在语法错误。 显然,问题出在引用上。 但一些谷歌搜索表明,使用参数是处理引号的方法。 如果类型是 TEXT 而不是 VARCHAR,SqlParameter 效果很好。
除了手动将字符串中的引号符号数量加倍之外,还有其他解决方案吗?
更新:我尝试在 SQL Management Studio 中手动编辑此字段,但它不允许在 VARCHAR 字段中使用单引号。 这在SQL中正常吗?
I'm trying to fix single quote bug in the code:
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;
The bug is that if idx="that's", the SQL fails saying that there is a syntax error. Obviously, the problem is in the quote.
But some googling shows that using parameters is the way to work with quotes. And SqlParameter works well, if type is TEXT and not VARCHAR.
There are any solutions other than manually doubling number of quote symbols in the string?
Update: I tried to manually edit this field in SQL Management Studio and it didn't allow single quotes in VARCHAR field. It this normal in SQL?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我怀疑问题是您的表名称中出现了引号,或者 idx 听起来更像是数字类型的名称而不是字符类型。
根据您的更新,我建议您检查 Management Studio 中表上的额外约束。
I suspect the problem is either a quote getting in your table name, or that idx sounds more like the name of a number type than a character type.
Based on your update, I suggest you check for extra constraints on the table in management studio.
说实话,我从来没有遇到过 SqlParameters 的问题。 但请尝试以下操作:
http://msdn .microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue.aspx
这应该可以为您正确工作和编码。
To be honest I have never had a problem with SqlParameters. But try the following:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue.aspx
This should work and encode correctly for you.
如果您确定它是一个引号问题,那么
C# 代码:
将解决该问题。
If you are sure its a quotes prob then,
C# code:
would solve the problem.
对不起。
问题出在 SQL 触发器的代码中。 删除它们后,一切正常。
Sorry.
The problem was in SQL trigger's code. After removing them, all worked fine.