-2

What kind of changes i can make to this code to protect against sql injection?

private void button1_Click(object sender, EventArgs e)
        {
               string query = "INSERT INTO person (name_,age_)VALUES('" + txtFirstname.Text + "','" + int.Parse(txtAge.Text) + "')";
               DB.OpenConnection();
               DB.SqlQuery = query;
               DB.ExecuteQuery();
               DB.CloseConnection();
        }
Jason Groulx
  • 400
  • 2
  • 10
Joel
  • 91
  • 7
  • 3
    https://stackoverflow.com/q/7505808/1070452 If you just type `c# sql parameters` into google you get many, many millions of hits – Ňɏssa Pøngjǣrdenlarp May 13 '20 at 20:21
  • Does this answer your question? [Why do we always prefer using parameters in SQL statements?](https://stackoverflow.com/questions/7505808/why-do-we-always-prefer-using-parameters-in-sql-statements) – Christopher Moore May 14 '20 at 00:14

1 Answers1

0

Something like below

    string query = "INSERT INTO person (name_,age_) VALUES(@name,@age)";
    MySqlCommand m = new MySqlCommand(query);
    m.Parameters.AddWithValue("@name", txtFirstname.Text);
    m.Parameters.AddWithValue("@age", int.Parse(txtAge.Text));

(OR)

m.Parameters.Add(new MySqlParameter("@name", txtFirstname.Text));
Rahul
  • 76,197
  • 13
  • 71
  • 125