我正在使用MySQL連接器/網絡,我想寫一個名稱將在運行時指定的表的查詢。什麼是在運行時動態選擇表名的最佳方式?
這個例子是把我的頭(未測試)的頂部:
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...
}
}
因爲我不認爲你可以在查詢參數表名,我用了一個枚舉,而不是一個字符串功能參數限制SQL injection的可能性。
這似乎是一個很好的方法嗎?有沒有更好的辦法?
.net是否不支持向枚舉類型添加額外屬性? – Jherico 2010-01-15 19:16:02
你的意思是像Table1 =「table_1」等,如果是這樣,那麼你只能使用像int和long這樣的整型。 – 2010-01-15 19:19:18