2009-02-13 67 views
0

我有一個HTML文本框,其中包含一些我需要執行的SQL代碼。我能夠從文本框中檢索實際的代碼,但我不知道如何去執行代碼。任何簡單和優雅的方式使用C#3.5?如何使用c#3.5運行SQL代碼?

+0

親愛的上帝,不,不要讓用戶直接將sql輸入到文本框! – 2009-02-13 14:55:15

+0

澄清:這不僅僅是安全問題,儘管這是一筆巨大的交易。對於那些善意的用戶來說,放入一個性能不佳的查詢,對你的服務器進行管理,並且有效地在你的數據庫上創建一個拒絕服務,這是非常容易的。 – 2009-02-13 14:57:41

+0

不想擊敗死馬,但瞭解這是一個可怕的想法是非常重要的。 – 2009-02-13 15:33:33

回答

15

不執行代碼的文本框

,除非你真的相信正在輸入的內容。

如果你這樣做,這樣做:

SqlConnection con = new SqlConnection("Your connection string"); 
con.Open(); 
SqlCommand cmd = new SqlCommand(TexdtBox1.Text, con); 
cmd.ExecuteNonQuery(); 
con.Close() 

注意,這將不會返回任何東西,僅僅指剛運行查詢。如果你想返回數據,你需要一個SqlDataAdaptor或者SqlDataReader。

+0

關於'trusing'輸入的第一條語句 – tvanfosson 2009-02-13 14:53:56

0

這取決於您要執行的數據庫的類型。如果我可以假設你想談論到SQL Server數據庫,看看下面的類:

0

這裏有一個小(未經測試的未經檢驗的,因爲就在SO文本框中鍵入)的示例代碼:

using System.Data; 

namespace MyGreatNamespace 
{ 
    class MyGreatClass 
    { 
     static public DataTable executeTable(string query) 
     { 
      return executeTable(query, null, null); 
     } 

     static public DataTable executeTable(string query, string[] params, object[] values) 
     { 
        DataTable myTable = new DataTable(); 
      using (SqlConnection connection = new SqlConnection(myConnectionString)) 
      using(SqlCommand command = new SqlCommand(connection)) 
      { 
       command.CommandType = CommandType.Text; 
       command.CommandText = myQuery; 

       if (parameters.Count == values.Count && parameters.Count > 0) 
       { 
        for(int i = 0; i < parameters.Count; i ++) 
        { 
         command.addParameterWithValue(parameters[i], values[i]); 
        } 
       } 

       using(SqlDataAdapter adapter = new SqlDataAdapter(command)) 
       { 
        adapter.Fill(out myTable); 
       } 
      } 
      return myTable; 
     } 
    } 
} 
0

我不會推薦它,但如果這樣做,至少驗證了SQL輸入從SELECT開始,不包含任何分號(;)或註釋字符( - 和/ *)。