I have a class, ValuesField
, which manages values for ComboBoxes.
The constructor specifies a database table from which the values can be retrieved, along with two fields from which to SELECT
data.
public ValuesField(string databaseTable, string idField, string valueField)
{
this.databaseTable = databaseTable;
this.idField = idField;
this.valueField = valueField;
}
My method, GetValues()
retrieves this data (from which a ComboBox can then be populated). I was constructing the CommandText
as a simple string, however I wanted to use a parameterized query for safety.
The simple string command -
dbCommand.CommandText = "SELECT " + idField + "," + valueField + " FROM " +
databaseTable + " ORDER BY " + valueField;
The parameterized query -
dbCommand.CommandText = "SELECT @idField, @valueField FROM @databaseTable
ORDER BY @valueField";
dbCommand.Parameters.AddWithValue("@idField", idField);
dbCommand.Parameters.AddWithValue("@valueField", valueField);
dbCommand.Parameters.AddWithValue("@databaseTable", databaseTable);
dbReader = dbCommand.ExecuteReader();
The parameterized query throws a MySqlException
on ExecuteReader()
with the Message 'You have an error in your SQL syntax'.
I checked the value of the
CommandText
at the point the Exception is thrown and it (using the Watch) and theCommandText
still shows as"SELECT @idField, @valueField FROM @databaseTable ORDER BY @valueField"
- so I am not sure how to examine the syntax for any obvious errors as I would normally do.I see that this is apparently not possible according to this answer.
Is there a way to view the actual CommandText
with the values included in order to diagnose syntax errors?
Is there a safe alternative to specify a table name, if indeed using a parameterized query is not possible?