2017-06-13 68 views
1

我在學校有一個項目,而且我需要將我的註冊頁面與數據庫連接起來。 我有這樣的代碼:關鍵字'add'附近的語法不正確

if (Request.Form["submit"] != null) 
{ 
    string fName = Request.Form["fName"]; 
    string lName = Request.Form["lName"]; 
    string Passwod = Request.Form["Passwod"]; 
    string email = Request.Form["email"]; 
    string add = Request.Form["add"]; 

    string RegStatus; 

    if ((fName == "") || (lName == "") || (Passwod == "") || (email == "") || (add == "")) 
    { 
     RegStatus = ("missing data or wrong data"); 
    } 
    else 
    { 
     string selectQuery = "SELECT * FROM " + "[Users]"; 
     selectQuery += " WHERE "; 
     selectQuery += " email = '" + Request.Form["email"] + "'"; 

     if (MyAdoHelper.IsExist(selectQuery)) 
     { 
      RegStatus = ("email does not exists"); 
     } 
     else 
     { 
      string insertQuery = "INSERT INTO [Users] (fName,lName,Passwod, email,add) VALUES ('"; 
      insertQuery += fName + "', '" + lName +"','" + Passwod + "', '" + email + "','" + add +"')"; 
      Response.Write(insertQuery); 
      MyAdoHelper.DoQuery(insertQuery); 
      RegStatus = ("Registeration was successful "); 
     } 
    } 

    Response.Write(RegStatus); 
    Response.End(); 
} 

填充數據(運行後)我得到的錯誤是:

System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'add'.

源錯誤:

public static void DoQuery(string sql) 
    { 
     SqlConnection conn = ConnectToDb(); 
     conn.Open(); 
     SqlCommand com = new SqlCommand(sql, conn); 
     com.ExecuteNonQuery(); //* it says the error is in this line. //* 
     com.Dispose(); 
     conn.Close(); 
    } 
+3

如果你正在學習SQL,學會用參數化查詢。不要查詢字符串。這隻會導致語法錯誤和SQL注入漏洞。 –

回答

3

add是SQL關鍵字。如果你有一個字段命名爲這樣你必須使用括號:

INSERT INTO [Users] (fName,lName,Passwod, email,[add]) VALUES... 

此外,如已經評論,使用參數,而不是字符串連接是非常重要的:

+0

ty man。完美地工作! – Nyrre

相關問題