如何在数据库中插入特殊字符作为名称的一部分 [英] how to insert special character as a part of name in database

查看:88
本文介绍了如何在数据库中插入特殊字符作为名称的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好

目前,我有一个表单名称``添加类别'',其中我有一个字段名称:``添加类别文本框'':我在其中插入字母字符(即a-z或A-Z).所有字母字符均已成功存储在数据库中.但是当我尝试在数据库中插入另一个字符撇号('')时,例如:O''真正的消息是这样的:


``really''附近的语法不正确.
字符串后的右引号.


我正在使用sql server作为数据库.

请帮助我

hello

Currently i have one form name Add Category where i have one field name : Add Category_textbox: where i insert alpha characters (i.e. a-z OR A-Z).All the alpha character successfully stores in database. but when i try with another character apostrophe ('') to be inserted in database.example: O''Really then the message comes like this:


Incorrect syntax near ''really''.
unclosed quotation mark after the character string".


i am using sql server as database.

plz help me out

推荐答案

单引号是它自己的转义字符.因此,您可以在
中使用2 字符串,表示将其视为1个文字单引号.
但是相反,我建议您使用参数化查询来避免此问题.
您应该始终使用它来防止SQL注入
攻击是最重要的原因.
解决您的问题的方法是在 SQL注入 [使用SQL转义序列 [在编写sql查询时如何逃脱特殊字符 [
The single quote is its own escape character. So you would use 2 in a
string, to signify to treat it as 1 literal single quote.
But instead I suggest you to use parameterized queries to avoid this problem.
You should always use it to prevent SQL injection
attacks that is the most important reason for it.

The solution to your problem is in this link[^].

But check out these links as well;
SQL injection[^]
Using SQL Escape Sequences[^]
how does one escape special characters when writing sql queries[^]


您可以使用在sqlcommand中定义参数来创建插入查询:
You can create an insert query with defining parameters in sqlcommand:
SQLCommand cmd = new SQLCommand("Insert into Category(id, name) values(@id, @name)" , con);



其中con SQLConnection对象.

您可以如下定义参数:



Where con is the SQLConnection object.

You can define parameters as follows:

SQLParamter param1 = new SQLParamter("@id","1");
SQLParamter param2 = new SQLParamter("@name","O''Really");



在上面的SQLCommand中添加参数:



Add the parameters in above SQLCommand:

cmd.Parameters.add(param1);
cmd.Parameters.add(param2);



执行命令:



Execute the command:

cmd.ExecuteNonQuery();



希望这会对您有所帮助.



Hope this will help you.


如果您要在SQL Server数据库中插入单引号,则需要将其与第二个单引号配对以进行转义(只有一个单引号会被删除).已存储).因此,如果您尝试插入"string"",则需要将其更改为"string"''".
If you are inserting a single quote into a sql server database, you need to pair it with a second single quote to escape it (only one single quote will be stored). So if you are trying to insert "string''", you need to change it to "string''''".


这篇关于如何在数据库中插入特殊字符作为名称的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆