2012-01-06 69 views
-5

我正在添加一個輸入框到我的網站,我作爲管理員可以輸入sql select語句,我試着圍繞代碼執行select來嘗試並捕獲語法錯誤但即使這樣,當出現語法錯誤時,我的網站會轉到「應用程序錯誤/」頁面。爲什麼試着抓住不抓住Sql語法錯誤

我不明白我在做什麼錯。我正在開發Asp.net v4。

執行自定義SQL命令的代碼如下;

try 
{ 
     //edtSQL.Text = "WHRE Field='Value'" 
     //The Resulting SQL Command will be incorrect because of incorrect syntax 
     SqlDataSource1.SelectCommand = "SELECT * FROM DataTable " + edtSQL.Text; 
     SqlDataSource1.Select(new DataSourceSelectArguments()); 
} 
catch(Exception ex) 
{ 
     //Bad Syntax should be caught here, but it is not. This never get called 
     // even when there is a syntax error. 
     lblQueryStatus.Text = "Error, can't execute SQL statment"; 
} 

相反,如果顯示錯誤消息的標籤,該網站提供了一個錯誤並且去默認的站點錯誤頁面。

+0

你能提供你的代碼,特別是你的點擊處理程序按鈕/ – Arbiter 2012-01-06 21:13:36

+1

你確定一個異常沒有被其他地方扔?你捕捉所有的異常或只是'SqlException's? – 2012-01-06 21:13:46

+2

請發佈您的相關代碼。你期望發生什麼? – Oded 2012-01-06 21:13:47

回答

0

上述代碼中的catch實際上確實捕捉到異常。在例外情況下,將選擇命令設置爲默認值,即確保可以正常工作。

SELECT * FROM Database 

並執行選擇。原因是當頁面做回發試圖執行已經爲它設置的select語句時,並沒有試圖繞過這個(因爲它在另一個上下文中),這就是爲什麼服務器默認爲「應用程序/錯誤」頁面中。

的代碼看起來應該是這樣

try 
{ 
    //edtSQL.Text = "WHRE Field='Value'" 
    //The Resulting SQL Command will be incorrect because of incorrect syntax 
    SqlDataSource1.SelectCommand = "SELECT * FROM DataTable " + edtSQL.Text; 
    SqlDataSource1.Select(new DataSourceSelectArguments()); 
} 
catch(Exception ex) 
{ 
    SqlDataSource1.SelectCommand = "SELECT * FROM DataTable"; //This will work for sure 
    SqlDataSource1.Select(new DataSourceSelectArguments()); 
    lblQueryStatus.Text = "Error, can't execute SQL statment"; 
} 
+0

在附註中,您絕對應該使用SqlParameters; '「SELECT * FROM DataTable」+ edtSQL.Text;'讓你爲注入攻擊打開大門。 – Will 2012-01-16 19:36:01

+0

謝謝。我會研究如何做到這一點。 – 2012-01-16 19:51:00