Preventing SQL injection on insert

安稳与你 提交于 2019-12-04 07:32:53

问题


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.

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();
 }

回答1:


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";


来源:https://stackoverflow.com/questions/17818473/preventing-sql-injection-on-insert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!