Aps Sanj Aps Sanj - 1 year ago 167
C# Question

Set table name and column name dynamically in SQL statement

I am new to C#. I have to get inputs from windows form and execute a sql statement. Here I have to get the table name and column name from user inputs.
I wrote a code like this.

string ment = String.Format("update {0} set {1} ='" + radioButton1.Text + "' where RoomId='" + textBox8.Text + "'", textBox7.Text, comboBox1.SelectedItem);
cmd = new SqlCommand(ment, con);
cmd.ExecuteNonQuery();


This gives an exception.


It says "Incorrect syntax near '-'".


Any idea on what I missed?

Han Han
Answer Source

Your table name or column name might have inproper characters. Wrap them in with character ` in MySQL or brackets in MSSQL.

MSSQL version.

string ment = String.Format("update [{0}] set [{1}] ='" + radioButton1.Text + "' where RoomId='" + textBox8.Text + "'", textBox7.Text, comboBox1.SelectedItem); 
cmd = new SqlCommand(ment, con);
cmd.ExecuteNonQuery();

MySQL version.

string ment = String.Format("update `{0}` set `{1}` ='" + radioButton1.Text + "' where RoomId='" + textBox8.Text + "'", textBox7.Text, comboBox1.SelectedItem); 
cmd = new SqlCommand(ment, con);
cmd.ExecuteNonQuery();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download