2012-03-08 18 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

2

このコードは動作するはずですあなたのコードは

  • SQLインジェクション攻撃に対して脆弱である

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

    WARNING

    • は、パラメータ化されたSQLを使用することを検討してください。これにより、SQLインジェクションの脆弱性が回避されます。

    VB.NETこれはあなたのC#

    1. SQLコマンドを作成するために簡単に変換する必要があります

      にSQL Serverのクエリを実行する方法 - あなたは、接続を設定されていませんSQLCommandのプロパティ。コード行を追加することなくこれを行うことができます。 これがエラーの原因です。

      myCommand = New SqlCommand("Insert Into MyTable values (@value1, @value2)", MyConnection) 
      
      • 注:VALUE1、@の値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. それがあるべき

      ''' <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

    +1

    @Crematorio「本当に生きていけないだろう」は「有名な最後の言葉」のカテゴリにあります、私は恐れています。 –

    +1

    @Crematorioパラメータ化されたSQLを使用する負担はありません。私のコードを見て、あなたは自分自身に恩恵を与えるでしょう。 –

    0

    あなたのSQLコマンドを実行するための関数を作成します(私はあなたがフィールドに電子メールを送りだと思うので、単一引用符が必要とされる文字列YPEであろう)

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

    技術的に「正しい」とはいえ、見た目のSQLインジェクションについての警告はほとんどありませんが、最低限の価値があります。 –

    +0

    @ Christian.K私はちょうどどこにエラーが示唆されました –

    +0

    はい私はそう思った、それは私が言った理由は、ほとんどの投票に値する。 –