0

I want to use a variable and pass this value into an SQL statement as part of the table name, however, I'm not sure whether the method I've used is secure (even though it works). If not, how should I go about it?

    string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
    MySqlConnection conn = new MySqlConnection(connStr);
    string table = "1";
    MySqlCommand comm = new MySqlCommand("INSERT INTO " + table + "_tests (user_id, score, time) VALUES (@user_id, @score, @time)", conn);
    comm.Parameters.Add("@user_id", MySqlDbType.VarChar);
    comm.Parameters["@user_id"].Value = "2";
    comm.Parameters.Add("@score", MySqlDbType.VarChar);
    comm.Parameters["@score"].Value = txtScore.ToString();
    comm.Parameters.Add("@time", MySqlDbType.VarChar);
    comm.Parameters["@time"].Value = txtTime.ToString();

Updated:

    int tableID = Convert.ToInt32(Session["TestModuleID"].ToString());
    MySqlCommand comm = new MySqlCommand("INSERT INTO " + tableID.ToString() + "_tests (user_id, score, time) VALUES (@user_id, @score, @time)", conn);
3
  • 1
    Where does the value come from? Commented Jul 12, 2014 at 19:11
  • @juergend Currently it's hardcoded as "1" but I plan to change that to string table = Session["TestModuleID"].ToString(); Commented Jul 12, 2014 at 19:16
  • As Ollie said - convert the user input to an int. Commented Jul 12, 2014 at 19:20

1 Answer 1

2

You are correct that what you have works. As you have probably guessed, you can't use a Parameter for a table name.

The safety issue raised by your code can be removed by redeclaring your table variable as an integer, like so...

int table = 1;
MySqlCommand comm = new MySqlCommand (
       "INSERT INTO " + table.ToString() +   
       "_tests (user_id, score, time) VALUES (@user_id, @score, @time)", conn);

This will keep anything non-numeric from creeping into your query. There are other ways to control the value of your table variable as well.

Sign up to request clarification or add additional context in comments.

1 Comment

I've included the revised code in my original post. The variable value is derived from a Session object so nothing should creep in but I guess that is sufficiently robust?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.