且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

带有额外字符的字符串

更新时间:2023-11-21 21:58:04

我假设您使用的是简单的SQL查询,例如
I assume that you are using a simple SQL query such as
SqlCommand cmd = new SqlCommand("INSERT INTO tab (field1) VALUES (" + textBox1.Text + ")");

数据库抱怨了吗?

恭喜你!这留下了一个称为"SQL注入"的空缺.

特殊字符的添加使数据库将它们作为命令的一部分进行处理.例如,如果在文本框中输入你好";"DROP TABLES选项卡",则不要执行此操作,SQL将会显示:

And the database complains?

Congratulations! This is leaving an opening known as "SQL Injection".

The addition of special characters causes the database to process them as part of a command. For example (DO NOT DO THIS) if you enter "hello);DROP TABLES tab" into your text box, the SQL would see:

"INSERT INTO tab (field1) VALUES (hello);DROP TABLES tab;)"

作为单个命令.
因为;"是语句终止符,所以SQl将此视为两个命令:INSERT,后跟DROP TABLES.它将您的名字插入为"hello",然后删除选项卡表.

不要这样使用参数化查询:

as a single command.
Because '';'' is a statement terminator, SQl sees this as two commands: An INSERT, followed by a DROP TABLES. It inserts your name as "hello", and then deletes the tab table.

Don''t do it this way. Use a parameterized query:

SqlCommand cmd = new SqlCommand("INSERT INTO tab (field1) VALUES (@NAME)");
cmd.AddWithValue("@NAME", textBox1.Text);


这样您的问题就会消失,而不是您的表...


And you problem will disappear, instead of your tables...


您可以定义一个正则表达式来定义可接受的(通常更彻底的) .
根据所使用的技术(您无需说说此ASP.NET,Winforms还是WPF),您将需要在相关的验证器中使用正则表达式来防止用户在更正输入之前继续操作.

您还应该在插入之前检查输入,如果无效则拒绝,将值作为SQL参数传递以停止SQL注入攻击.
You can define a regular expresssion to defined what is either acceptable (generally more thorough) or unacceptable.
Depending on the technology used (you don''t say whether this ASP.NET, Winforms or WPF) you will need to use the regex in the relevant validator to prevent the user continuing before the input is corrected.

You should also check the input before insertion and reject if not valid, and pass the value as an SQL parameter to stop SQL injection attacks.


数据是什么变量类型?????
what is the data type of variable?????