2012-05-29 68 views
0

我有我的SqlCommand一切,我打開網頁的問題,我得到的錯誤語法錯誤:SQLEXCEPTION在Asp.net - 近「範」

System.Data.SqlClient.SqlException: Incorrect syntax near 'Van'. 

我無法找到問題,因爲「凡」只發現一旦整個項目,並在標題.. 這是我在Page_Load代碼:

using (SqlConnection con = new SqlConnection(RoleEnvironment.GetConfigurationSettingValue("DatabaseConnectionString"))) 
      { 
       var cmd = new SqlCommand("SELECT (SELECT Memo_ID, Dep_Name FROM Department WHERE (Department_ID = Staff.Depar_ID)) AS DepartmentName FROM Staff WHERE (FirstName + SPACE(1) + LastName = " + User.Identity.Name, con); 
       cmd.Connection.Open(); 
       var sqlReader = cmd.ExecuteReader(); 
       while (sqlReader.Read()) 
       { 

        String result = sqlReader.GetString(0); 
        DropDownList1.DataBind(); 
        DropDownList1.Items.FindByValue(result).Selected = true; 
        //Fill some data like : string result = sqlReader("SomeFieldName"); 
       } 
       sqlReader.Close(); 
       cmd.Connection.Close(); 
       cmd.Dispose(); 
      } 

數據庫ConnectionString的是正確的,因爲它適合我的所有其他網頁...我試圖讓一個員工工作的部門,因此他/她只能從t中查看備忘錄繼承人自己的部門。

+0

。在你的選擇查詢的問題。放一個斷點並複製查詢並嘗試在sql server查詢瀏覽器中運行它 – Devjosh

+1

不要構建像這樣的查詢 - 您很容易受到SQL注入的影響。見[媽媽的漏洞](http://xkcd.com/327/) – Filburt

+0

對不起..我是一個正式的白癡..感謝您的幫助,它現在工作:)查詢確實是錯誤的,我不會寫我的問題就這樣了! :) SORRY!但我只是測試它.. :) – Yunieke

回答

1

您需要在提供姓氏後關閉圓括號。

SELECT (SELECT Memo_ID, Dep_Name FROM Department 
WHERE (Department_ID = Staff.Depar_ID)) AS DepartmentName 
FROM Staff WHERE (FirstName + SPACE(1) + LastName = 'xxx') 

這是它應該是什麼樣子:

using (SqlConnection con = new SqlConnection(RoleEnvironment.GetConfigurationSettingValue("DatabaseConnectionString"))) 
     { 
      var cmd = new SqlCommand("SELECT (SELECT Memo_ID, Dep_Name FROM Department WHERE (Department_ID = Staff.Depar_ID)) AS DepartmentName FROM Staff WHERE (FirstName + SPACE(1) + LastName = '" + User.Identity.Name + "')", con); 
      cmd.Connection.Open(); 
      var sqlReader = cmd.ExecuteReader(); 
      while (sqlReader.Read()) 
      { 

       String result = sqlReader.GetString(0); 
       DropDownList1.DataBind(); 
       DropDownList1.Items.FindByValue(result).Selected = true; 
       //Fill some data like : string result = sqlReader("SomeFieldName"); 
      } 
      sqlReader.Close(); 
      cmd.Connection.Close(); 
      cmd.Dispose(); 
+0

非常感謝你:)! – Yunieke

0

您需要引用姓氏。您可能也想要轉換爲參數化查詢。

0

我會期待你的WHERE子句用引號括了User.Identity.Name

WHERE (FirstName + SPACE(1) + LastName = '" + User.Identity.Name + "'" ... 

可以「麪包車」是在用戶名?

這不是一個非常安全的查詢要麼 - 但SQL注入的另一個問題!

+0

我會照顧SQL注入,沒問題;) – Yunieke

相關問題