Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

c# - Preventing SQL injection on insert

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...