防止在插入时进行SQL注入 [英] Preventing SQL injection on insert

查看:82
本文介绍了防止在插入时进行SQL注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一些防止SQL注入的技巧.在一个论坛上告诉我我的代码不安全,我正在寻找一个足够好的人来帮助我解决该问题.

I am looking for some tips to prevent SQL injection. I was told on a forum my code is not safe and am looking for someone nice enough to help me fix that.

我有一个Web表单,提交后转到aspx.cs页面,并将数据插入到ms sql数据库中.

I have a webform and on submit it goes to the aspx.cs page and inserts the data into a ms sql database.

protected void Submit_Click(object sender, EventArgs e)
    {
        string FullStartTime = StartTimeHourList.SelectedValue + ":" + StartTimeMinuteList.SelectedValue + " " + StartTimeAMList.SelectedValue;
        string FullEndTime = EndTimeHourList.SelectedValue + ":" + EndTimeMinuteList.SelectedValue + " " + EndTimeAMList.SelectedValue;

        OleDbConnection conn;
        OleDbCommand cmd;
        conn = new System.Data.OleDb.OleDbConnection("");
        cmd = new System.Data.OleDb.OleDbCommand();
        conn.Open();
        cmd.Connection = conn;
        var sql = String.Format(@"INSERT INTO FormTable1 (Nonprofit, Contact, Phone, Email, Event, StartDate, EndDate, StartTime, EndTime, Place, Comments, SubmitDate) values 
                                                            ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}')",
                                                           NonprofitTxtBox.Text, ContactTxtBox.Text, PhoneTxtBox.Text, EmailTxtBox.Text, EventTxtBox.Text,
                                                           StartDateTxtBox.Text, EndDateTxtBox.Text, FullStartTime, FullEndTime, PlaceTxtBox.Text, CommentsTxtBox.Text, DateTime.Now);
        cmd.CommandText = sql;
        cmd.ExecuteNonQuery();
        conn.Close();
 }

推荐答案

最直接的解决方法是简单地通过将字符串串联在一起而不是使用params来构建sql.如果您使用的是SqlCommand,则可以执行以下操作,否则按照@MarcB的建议进行操作

The most straightforward fix is to simply not build sql by concatenating strings together, and instead using params. If you're using SqlCommand you can do the following, otherwise do as @MarcB suggested

SqlCommand cmd = new SqlCommand("INSERT dbo.Table (field1, field2, field3) VALUES (@f1, @f2, @f3)", conn);

cmd.Paramters.Add("@f1", SqlDbType.VarChar, 50).Value = "abc";
cmd.Paramters.Add("@f2", SqlDbType.Int).Value = 2;
cmd.Paramters.Add("@f3", SqlDbType.VarChar, 50).Value = "some other value";

这篇关于防止在插入时进行SQL注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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