C#.net背后的代码中的sql命令 [英] sql command in code behind C#.net

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

问题描述

如何在sql命令中调用asp参数.

exp:cmd.CommandText = "SELECT name FROM server WHERE code="+TextBox1.Text;

How to call an asp parameter in a sql command.

exp: cmd.CommandText = "SELECT name FROM server WHERE code="+TextBox1.Text;

Is it correct?

推荐答案

这取决于表["服务器]的列[" 代码]的数据类型].

如果Data-Type为Int/Numeric,则下面的代码应该起作用.
cmd.CommandText = "SELECT name FROM server WHERE code="+TextBox1.Text;

如果Data-Type为Varchar/Non-Numeric,请尝试如下操作.
cmd.CommandText = "SELECT name FROM server WHERE code=''" + TextBox1.Text + "''";

但是,我不建议您进行内联查询.而是使用参数化查询.因为普通的内联查询是SQL注入的邀请.
It depends on Data-Type of your Column["code"] of Table["server"].

If Data-Type is Int/Numeric, then below code should work.
cmd.CommandText = "SELECT name FROM server WHERE code="+TextBox1.Text;

In case Data-Type is Varchar / Non-Numeric then try as below.
cmd.CommandText = "SELECT name FROM server WHERE code=''" + TextBox1.Text + "''";

However, I don''t recommend in-line queries to you. Instead use parametrized query. Because plain inline query is an invite for SQL-Injection.
string sqlConnectString = "YourConnectionString";
string sqlSelect = "SELECT name FROM server WHERE code= @CodeValue";

SqlConnection sqlConnection = new SqlConnection(sqlConnectString);
SqlCommand sqlCommand = new SqlCommand(sqlSelect, sqlConnection);

sqlCommand.Parameters.Add("@CodeValue", System.Data.SqlDbType.Int);// Set SqlDbType based on your DB column Data-Type

 sqlCommand.Parameters["@CodeValue"].Value = TextBox1.Text;

SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCommand);
DataTable sqlDt = new DataTable();
sqlDa.Fill(sqlDt);


始终使用参数化查询!
您当前的解决方案不是sql注入安全的方法.
实际上,添加参数非常容易.
Always use parameterized queries!
Your current solution is not sql injection safe.
Adding parameters is quite easy in fact.
cmd.CommandText = "SELECT name FROM server WHERE code = @code";
cmd.Parameters.AddWithValue("@code", TextBox1.Text);


.NET/SQL现在将使用正确的值替换@code. SQL注入,更干净的代码,没有查询的机会将被缓存,从而导致更好的性能.
每个人都赢了! :)


.NET/SQL will now replace @code with the correct value. No chance for SQL injection, cleaner code, query is cached which causes better performance.
Everyone wins! :)


请参阅此
http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson06.aspx [ ^ ]
Refer this
http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson06.aspx[^]


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

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