如何使用sql参数代替 [英] how to use sql parameters instead

查看:114
本文介绍了如何使用sql参数代替的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种代码方法,但我想使用参数来防止sql注入..怎么做?



这是我的代码:



  if (cn.State == ConnectionState.Closed)cn.Open( ); 
cm.Connection = cn;
if (comboBox3.Enabled == true
{
string searchFor2 = comboBox1.Text;
string searchFor3 = comboBox2.Text;
string selectSql = SELECT + searchFor2 + + searchFor3 + FROM itmsparts;
SqlCommand com = new SqlCommand(selectSql,cn);
尝试
{
使用(SqlDataReader read1 = com.ExecuteReader ())
{
while (read1.Read())
{
ListViewItem parent = listView1.Items。添加(read1 [ 0 ]。ToString());
parent.SubItems.Add(read1 [ 1 ]。ToString());
}
}
}
最后
{

}
}

解决方案

使用参数化查询是一个非常正确的想法,并且显示的代码不是。请参阅: http://msdn.microsoft.com/en-us/library/ff648339.aspx [ ^ ]。



另见我过去的答案:

EROR IN com.ExecuteNonQuery(); [ ^ ],

你的名字没有显示名称? [ ^ ]。



通过串联从UI获取的字符串组成的查询。不仅重复的字符串连接是低效的(因为字符串是不可变的;我是否必须解释为什么它会使重复连接变坏?),但是,更重要的问题是,它打开了 SQL注入。用户可以在UI中编写任何内容,包括一些SQL片段。你明白了吗?具体方法如下: http://xkcd.com/327



-SA

I have this approach of code but I want to use parameters instead to prevent sql injection .. how to do that ?

here's my code :

if (cn.State == ConnectionState.Closed) cn.Open();
            cm.Connection = cn;
            if (comboBox3.Enabled == true)
            {
                string searchFor2 = comboBox1.Text;
                string searchFor3 = comboBox2.Text;
                string selectSql = "SELECT " + searchFor2 + ", " + searchFor3 + " FROM itmsparts";
                SqlCommand com = new SqlCommand(selectSql, cn);
                try
                {
                    using (SqlDataReader read1 = com.ExecuteReader())
                    {
                        while (read1.Read())
                        {
                            ListViewItem parent = listView1.Items.Add(read1[0].ToString());
                            parent.SubItems.Add(read1[1].ToString());
                        }
                    }
                }
                finally
                {

                }
            }

解决方案

Using parametrized query is quite a right idea, and the code shown is not. Please see: http://msdn.microsoft.com/en-us/library/ff648339.aspx[^].

See also my past answers:
EROR IN UPATE in com.ExecuteNonQuery();[^],
hi name is not displaying in name?[^].

The query composed by concatenation with strings taken from UI. Not only repeated string concatenation is inefficient (because strings are immutable; do I have to explain why it makes repeated concatenation bad?), but yes, way more important issue is that it opens the doors to SQL injection. The user can write anything in the UI, including some SQL fragment. Are you getting the idea? This is how: http://xkcd.com/327.

—SA


这篇关于如何使用sql参数代替的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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