INSERT INTO语句c#

时间:2015-07-14 11:09:39

标签: c# database oledb

我正在尝试使用C#创建订单表单,并尝试使用Visual Studio中的OleDB将此订单表单链接到Access数据库。 但是,当我尝试将订单保存到数据库时,我不断收到如下所列的语法异常

Error System.Data.OleDb.OleDbException (0x80040E14): Syntax error in INSERT INTO statement.
at
System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDb HResult hr)
at
System.Data.OleDb.OleDbCommand.ExecuteCommandTextFprSingleResult(tagD BPARAMS dbParams, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at AccessLoginApp.OrderForm.btn_Save_Click(Object sender, EventArgs e) in c:\Users\skyscarer\Documents\Visual Studio 2013\Projects\AccessLoginApp\OrderForm.cs: line 214

异常所指向的违规代码似乎在btn_Save_Click事件中。代码如下所示。

private void btn_Save_Click(object sender, EventArgs e)
    {
        try
        {
            connection.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = connection;
            command.CommandText = "insert into OrderForm(Customer Name, Address, Telephone Number, Post Code) values('" + customerName.Text + "', '" + addrBox.Text + "', '" + telephoneNumber.Text + "', '" + postCode.Text + "')";
            //command.CommandText = "insert into OrderForm (Customer Name, Address, Telephone Number, Post Code, Date Ordered, Due Date, Pick Up / Delivery, Item, Quantity, Size, Price) values ('"+customerName.Text+"', '"+addrBox.Text+"', '"+telephoneNumber.Text+"', '"+postCode.Text+"', '"+dateOrderedBox.Text+"', '"+dueDate.Text+"', '"+cBoxPickDeliver.Text+"', '"+itemBox.Text+"', '"+Quantity.Text+"', '"+sizeBox.Text+"', '"+price.Text+"')";
            command.ExecuteNonQuery();
            MessageBox.Show("Order Inserted into Database");
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error " + ex);
        }
    }

然而,异常指向的行只是command.ExecuteNonQuery()代码,所以我不确定异常试图说什么,因此我不确定我的代码有什么问题。 如果有人可以帮助我,我将不胜感激。干杯

1 个答案:

答案 0 :(得分:1)

尝试:

{{1}}

此外,您应该考虑使用参数,因为您对sql注入是开放的