Bushwacka
Bushwacka

Reputation: 915

variable name of table in select query

I would like to add into my query name of table from my string variable tablename. Is it possible in c#? I tried something like below. But it doesn't work. As you can see i want to set the FROM @tablename on scores

public void tableInsertTest()
        {

            MySqlConnection conn = null;

            string tablename = "scores";

            try
            {
                conn = new MySqlConnection(cs);
                conn.Open();

                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;
                cmd.CommandTimeout = 90;
                cmd.CommandText = (

                "INSERT INTO dailyrecords(recorddate, firstname, lastname, score ) " +
                "SELECT NOW(), name, lname, score FROM @tablename " );

                cmd.Prepare();

                cmd.Parameters.AddWithValue("@tablename", tablename);

                {
                    cmd.ExecuteNonQuery();
                }

                conn.Close();

            }

            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }
            return;
        }

Upvotes: 0

Views: 731

Answers (1)

Chris Midolo
Chris Midolo

Reputation: 191

cmd.CommandText = ("INSERT INTO dailyrecords(recorddate, firstname, lastname, score ) " +
                string.Format("SELECT NOW(), name, lname, score FROM {0} ", tablename) );

Your query is only a string and you have the value :)

Upvotes: 1

Related Questions