SQL命令,C# [英] SQL Command, C#

查看:71
本文介绍了SQL命令,C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

cmd.CommandText =  "SELECT * FROM Orders2 WHERE Monthname = '" + textBox1.Text.ToString() + "';";


推荐答案

否.
1)textBox1.Text已经是一个字符串:您不需要使用ToString.
2)除非要链接命令,否则不需要分号.
3)使用"SELECT * FROM"被认为是不好的做法"-而是列出您想要的字段.通过不传输您不感兴趣的内容,可以节省空间和带宽.
4)无论如何不要添加您的文本.有充分的理由:
4 a)如果您的测试包含空格或其他字符,则它将被视为其他命令内容-无用.您可以通过将文本括在引号中来解决此问题.
4 b)您容易遭受意外或故意的SQL注入攻击(例如Google"Bobby Tables")
4 c)很快变得难以阅读.

而是使用参数化查询:
No.
1) textBox1.Text is a string already : you do not need to use ToString.
2) You don''t need the semicolon, unless you are chaining commands.
3) It is considered "bad practice" to use "SELECT * FROM" - instead, list the fields you do want. This saves space and bandwidth by not transferring stuff you aren''t interested in.
4) Don''t add your text like that anyway. There are good reasons:
4 a) If your test contains spaces, or other characters then it will be treated as further command stuff - not helpfull. You can get round this by enclosing the text in quotes.
4 b) You leave yourself wide open to an accidental or deliberate SQL Injection attack (Google "Bobby Tables" for an example)
4 c) It quickly becomes hard to read.

Instead, use parameterised queries:
cmd.CommandText = "SELECT useId, userName FROM Orders2 WHERE Monthname=@MN";
cmd.Parameters.AddWithValue("@MN", textBox1.Text);


这篇关于SQL命令,C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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