我需要在数据库中存储用户名和城市,它显示错误 [英] I need to store user name and city in the db it showns the error

查看:109
本文介绍了我需要在数据库中存储用户名和城市,它显示错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

protected void Button2_Click(object sender, EventArgs e)
    {
       // string query;
        string str = "Data Source=HIMANSHU-PC;Initial Catalog=new1;Integrated Security=True";
        SqlConnection con = new SqlConnection(str);
        con.Open();
        string query = "insert into table dbinfo values('" + TextBox1.Text + "','" + TextBox2.Text + "')";
        SqlCommand cmd = new SqlCommand(query,con);
        cmd.ExecuteNonQuery();
        con.Close();


    }

推荐答案

你首先做错了。通过串联从UI获取的字符串组成的查询。不仅重复的字符串连接是低效的(因为字符串是不可变的;我是否必须解释为什么它会使重复连接变坏?),但是有更重要的问题:它打开了通向良好的大门已知的漏洞称为 SQL注入



这是它的工作原理: http://xkcd.com/327 [ ^ ]。< br $>


TextBox1 TextBox2 中的文字可以是任何内容,包括...... SQL代码片段。



怎么办?只需阅读有关此问题和主要补救措施:参数化语句 http://en.wikipedia.org/ wiki / SQL_injection [ ^ ]。



使用ADO.NET,请使用: http:// msdn.microsoft.com/en-us/library/ff648339.aspx [ ^ ]。



请查看我过去的答案以获取更多详细信息:

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

hi name没有显示在名称中? [ ^ ]。



-SA
You are doing it wrong in first place. 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 there is way more important issue: it opens the doors to a well-known exploit called SQL injection.

This is how it works: http://xkcd.com/327[^].

The text in TextBox1 and TextBox2 can be anything, including… fragments of SQL code.

What to do? Just read about this problem and the main remedy: parametrized statements: http://en.wikipedia.org/wiki/SQL_injection[^].

With ADO.NET, use this: http://msdn.microsoft.com/en-us/library/ff648339.aspx[^].

Please see my past answers for some more detail:
EROR IN UPATE in com.ExecuteNonQuery();[^],
hi name is not displaying in name?[^].

—SA


这篇关于我需要在数据库中存储用户名和城市,它显示错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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