2011-06-17 14 views
2

我正在創建一個方法來通過傳遞一個搜索字段來從任何表中選擇id。如何將表作爲參數傳遞給MySqlCommand?

private int SelectId(string tabela, string campo, string valor) 
{ 
    int id = 0; 

    using (command = new MySqlCommand()) 
    { 
     command.Connection = conn; 

     command.Parameters.Add("@tabela", MySqlDbType.).Value = tabela; 
     command.Parameters.Add("@campo", MySqlDbType.Text).Value = campo; 
     command.Parameters.Add("@valor", MySqlDbType.VarChar).Value = valor; 

     command.CommandText = "SELECT `id` FROM @tabela WHERE @[email protected];"; 

     try 
     { 
      id = (int)command.ExecuteScalar(); 
     } 
     catch (MySqlException ex) 
     { 
      MessageBox.Show(ex.Number + " : " + ex.Message + command.CommandText); 
     } 
     catch (Exception) 
     { 
      throw; 
     } 
    } 

    return id; 
} 

但我得到一個關於語法錯誤的MySqlException。當我查看Exception消息時,它向我顯示帶引號表的查詢! 如何以不帶引號的形式傳遞表格作爲參數?

回答

6

大多數數據庫不會讓您通過參數指定表或列名稱。參數意味着的值爲。如果你真的需要這是動態的,你應該驗證輸入(它應該是一個已知的表名,在該表中有已知的列名),然後將其包含在SQL中。

+0

非常感謝,夥計們。現在我對參數化SQL有了更好的理解。 – programad 2011-06-19 19:31:22

2

我同意Jon。以下代碼示例將表名直接插入到腳本中,而不是作爲參數。請注意,您仍然需要驗證表和列名稱以防止SQL注入。我沒有在這裏列入,但我已經爲你評論存根。

private int SelectId(string tabela, string campo, string valor) 
    { 
     int id = 0; 

     using (command = new MySqlCommand()) 
     { 
      command.Connection = conn; 

      command.Parameters.Add("@campo", MySqlDbType.Text).Value = campo; 
      command.Parameters.Add("@valor", MySqlDbType.VarChar).Value = valor; 

      // TODO: Validate table name for parameter 'tabela' to prevent SQL injection 
      // TODO: Validate column name for parameter 'campo' to prevent SQL injection 

      command.CommandText = "SELECT `id` FROM " + tabela + " WHERE @[email protected];"; 

      try 
      { 
       id = (int)command.ExecuteScalar(); 
      } 
      catch (MySqlException ex) 
      { 
       MessageBox.Show(ex.Number + " : " + ex.Message + command.CommandText); 
      } 
      catch (Exception) 
      { 
       throw; 
      } 
     } 

     return id; 
    } 
相關問題