I am using MySQL Connector/Net and I want to write a query against a table whose name will be specified at runtime.
This example is off the top of my head (not tested):
public class DataAccess
{
public enum LookupTable
{
Table1,
Table2,
Table3
}
public int GetLookupTableRowCount(LookupTable table)
{
string tableName = string.Empty;
switch (table)
{
case LookupTable.Table1:
tableName = "table_1";
break;
case LookupTable.Table2:
tableName = "table_2";
break;
case LookupTable.Table3:
tableName = "table_3";
break;
default:
throw new ApplicationException("Invalid lookup table specified.");
}
string commandText = string.Concat("SELECT COUNT(*) FROM ", tableName);
// Query gets executed and function returns a value here...
}
}
Since I don't think you can parameterize a table name in a query, I used an enum rather than a string in the function parameter to limit the possibility of SQL injection.
Does that seem like a good approach? Is there a better way?