ASP.NET语法错误
本文关键字:错误 语法 NET ASP | 更新日期: 2023-09-27 18:27:02
我遇到了一个语法错误,似乎找不到答案,我希望有人能看到我缺少的东西。
我正试图使用以下代码在数据库中添加数据,但它抛出了一条语法错误消息,我真的不明白为什么。
这是我的代码:
// 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.example@email.com'.
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.example@email.com'.
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.example@email.com'.]
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
您的直接问题是需要将最后一个值用单引号括起来:
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);
插入电子邮件变量后,您缺少一个撇号
此代码应能在中工作
string sql = "INSERT INTO Applicant VALUES" +
"('" + first + "', '" + last +
"', '" + gender + "', '" + age + "', " + email + "');";
警告
- 您的代码易受SQL注入攻击
- 考虑使用参数化SQL。这将防止SQL注入漏洞
如何在VB.NET中运行SQL Server查询
这应该很容易翻译成你的C#
创建SQL命令-您没有设置SQLCommand的连接属性。您可以在不添加一行代码的情况下完成此操作这就是你犯错误的原因
myCommand = New SqlCommand("Insert Into MyTable values (@value1, @value2)", MyConnection)
- 注意:@value1,@value2——这些稍后会发挥作用。这些是SQL参数的占位符。这些会拯救你的屁股。
- 注意:@value1,@value2——这些稍后会发挥作用。这些是SQL参数的占位符。这些会拯救你的屁股。
插入参数值-您需要使用SQL参数,尽管您没有使用存储过程。
CMD.Parameters.Add("@value1", SqlDbType.Int).Value = CInt(TXT_BookdID.Text) CMD.Parameters.Add("@value2", SqlDbType.varchar, 500).Value = TXT_BookName.Text
创建一个函数来执行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
应该是(我认为你的电子邮件字段应该是字符串类型,所以需要单引号)
string sql = "INSERT INTO Applicant VALUES" +
"('" + first + "', '" + last +
"', '" + gender + "', '" + age + "', '" + email + "');";