2012-03-08 76 views
1

我得到一個語法錯誤,我似乎沒有找到答案,我希望有人能夠看到我缺少的東西。語法錯誤ASP.NET

我想通過使用下面的代碼在數據庫中添加數據,但它會引發語法錯誤消息,我真的不明白爲什麼。

這是我的代碼:

// Get data from textboxes. 
    string last = txtLastName.Text; 
    string first = txtFirstName.Text; 
    string gender = txtGender.Text; 
    string email = txtEmail.Text; 
     int age = int.Parse(txtAge.Text); 
    string pref = "";  
    // Compose SQL command string. 
    string sql = "INSERT INTO Applicant VALUES" + 
     "('" + first + "', '" + last + 
     "', '" + gender + "', '" + age + "', " + email + ");"; 

這是錯誤消息

Syntax error (missing operator) in query expression '[email protected]'. 

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Data.OleDb.OleDbException: Syntax error (missing operator) in query expression '[email protected]'. 

Source Error: 


Line 50:  // Create command object and execute insert statement. 
Line 51:  OleDbCommand command = new OleDbCommand(sql, c); 
Line 52:  command.ExecuteNonQuery(); 
Line 53:   
Line 54:  // Close connection. 

Source File: d:\DePaul\Winter 2012\IT 330\Projects\Proj5-Nicolaides\Proj5-Nicolaides\application-form.aspx Line: 52 

Stack Trace: 


[OleDbException (0x80040e14): Syntax error (missing operator) in query expression '[email protected]'.] 
    System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr) +992124 
    System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) +255 
    System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) +188 
    System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) +58 
    System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) +161 
    System.Data.OleDb.OleDbCommand.ExecuteNonQuery() +113 
    ASP.application_form_aspx.btnSubmit_Click(Object sender, EventArgs e) in d:\DePaul\Winter 2012\IT 330\Projects\Proj5-Nicolaides\Proj5-Nicolaides\application-form.aspx:52 
    System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111 
    System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110 
    System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10 
    System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13 
    System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36 
    System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565 

Version Information: Microsoft .NET Framework Version:2.0.50727.5448; ASP.NET Version:2.0.50727.5456 

回答

4

你眼前的問題是,你需要用單引號括您的最後一個值:

string sql = "INSERT INTO Applicant VALUES" + 
    "('" + first + "', '" + last + 
    "', '" + gender + "', '" + age + "', '" + email + "');"; 

你的LARGER問題是你容易受到SQL注入通過不使用參數化查詢。這將是謹慎的:

string sql = @"insert into application 
    values(@first, @last, @gender, @age, @email)"; 
command.Parameters.AddWithValue("@first", first); 
command.Parameters.AddWithValue("@last", last); 
command.Parameters.AddWithValue("@gender", gender); 
command.Parameters.AddWithValue("@age", age); 
command.Parameters.AddWithValue("@email", email); 
+0

正如我已經說過,這是一個測試應用程序,它不會上線。感謝您的幫助和關注 – Geo 2012-03-08 05:47:36

2

電子郵件變量插入後,您缺少撇號。

此代碼應工作

string sql = "INSERT INTO Applicant VALUES" + 
    "('" + first + "', '" + last + 
    "', '" + gender + "', '" + age + "', " + email + "');"; 

警告

  • 您的代碼很容易受到SQL注入攻擊
  • 考慮使用參數化SQL。這將防止SQL注入漏洞。

如何在VB.NET

這應該很容易轉換到C#

  1. 創建SQL命令運行SQL Server查詢 - 您沒有設置連接SQLCommand的屬性。你可以在不添加一行代碼的情況下做到這一點。 這是你錯誤的原因。

    myCommand = New SqlCommand("Insert Into MyTable values (@value1, @value2)", MyConnection) 
    
    • 注:@值1,@值2 - 這些進入遊戲後。這些是SQL參數的佔位符。這些可以節省你的屁股。

  2. 插入參數值 - 你需要利用SQL參數,儘管你沒有使用存儲過程中的事實。

    CMD.Parameters.Add("@value1", SqlDbType.Int).Value = CInt(TXT_BookdID.Text) 
    CMD.Parameters.Add("@value2", SqlDbType.varchar, 500).Value = TXT_BookName.Text 
    
  3. 創建一個函數來執行SQL命令

    ''' <summary>Executes a SqlCommand on the Main DB Connection. Usage: Dim ds As DataSet = ExecuteCMD(CMD) </summary>' 
    ''' <param name="CMD">The command type will be determined based upon whether or not the commandText has a space in it. If it has a space, it is a Text command ("select ... from .."), ' 
    ''' otherwise if there's just one token, it's a stored procedure command</param>' 
    Function ExecuteCMD(ByRef CMD As SqlCommand) As DataSet 
        Dim connectionString As String = ConfigurationManager.ConnectionStrings("main").ConnectionString 
        Dim ds As New DataSet() 
    
        Try 
         Dim connection As New SqlConnection(connectionString) 
         CMD.Connection = connection 
    
         'Assume that it's a stored procedure command type if there is no space in the command text. Example: "sp_Select_Customer" vs. "select * from Customers" 
         If CMD.CommandText.Contains(" ") Then 
          CMD.CommandType = CommandType.Text 
         Else 
          CMD.CommandType = CommandType.StoredProcedure 
         End If 
    
         Dim adapter As New SqlDataAdapter(CMD) 
         adapter.SelectCommand.CommandTimeout = 300 
    
         'fill the dataset' 
         adapter.Fill(ds) 
         connection.Close() 
    
        Catch ex As Exception 
         ' The connection failed. Display an error message.' 
         Throw New Exception("Database Error: " & ex.Message) 
        End Try 
    
        Return ds 
    End Function 
    
+0

我需要兩個單引號。我不使用參數,因爲它只是對未來項目的測試,所以它不會真正上線。感謝您的幫助和建議雖然:) – Geo 2012-03-08 05:42:06

+1

@Crematorio「不會真正去活」是在「着名遺言」的類別,恐怕。 – 2012-03-08 05:44:58

+1

@Crematorio使用參數化SQL不是一個負擔。仔細查看我的代碼,你會爲自己做個忙。 – 2012-03-08 05:51:01

0

它應該是(我想你的電子郵件字段將是字符串YPE所以單引號爲必填項)

string sql = "INSERT INTO Applicant VALUES" + 
    "('" + first + "', '" + last + 
    "', '" + gender + "', '" + age + "', '" + email + "');"; 
+0

雖然技術上「正確」,沒有任何關於明顯的SQL注入的警告,但這個_almost_值得投票反對。 – 2012-03-08 05:42:40

+0

@ Christian.K我剛剛被建議在哪裏出錯 – 2012-03-08 05:44:52

+0

是的,我認爲是這樣,這就是爲什麼我說_almost_值得投票。 – 2012-03-08 05:45:47