Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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();
 }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
417 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...