Search code examples
c#databaseoledb

Syntax Error in Insert Into Statement C# OleDb


I am creating an order form using C# OleDb and am having an issue with attempting to put the size value from a combo box in the order form into the database. The code that causes the issue is below.

 private void btn_Save_Click(object sender, EventArgs e)
    {
        try
        {
            connection.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = connection;
            command.CommandText = "insert into OrderForm(Size) values ('" + sizeBox.Text + "')";
            command.ExecuteNonQuery();
            MessageBox.Show("Order Inserted into Database");
            connection.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error " + ex);
        }
    }

This is the only piece of code that is causing me an issue and i've compared it to my other commandText lines of code that i've commented out to ensure that the syntax is correct and it looks okay to me. I have also checked to ensure that the field name listed into the commandText code and the field in the actual database are correct and it is. Any help on this issue will be greatly appreciated. Cheers

Edit: Syntax Error that the code is giving me Syntax Error


Solution

  • SIZE is a reserved word. You cannot use it as a field name unless you enclose it in square brackets, so your code should be written as

    private void btn_Save_Click(object sender, EventArgs e)
    {
        try
        {
            string sqlText = "insert into OrderForm([Size]) values (?)";
            using(OleDbConnection connection = new OleDbConnection(.....))
            using(OleDbCommand command = new OleDbCommand(sqlText, connection))
            {
                connection.Open();
                command.Parameters.Add("@p1", OleDbType.VarWChar).Value = sizeBox.Text;
                int rowsAdded = command.ExecuteNonQuery();
                if(rowsAdded > 0) 
                    MessageBox.Show("Order Inserted into Database");
                else
                    MessageBox.Show("No Order added to the Database");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error " + ex.Message);
        }
    }
    

    A part from enclosing the SIZE in square brackets I have changed a couple of things.

    First everytime you reach a database you use the using statement around the connection and other disposable object. This avoid memory leaks and expensive resouce utilization when they are not needed.

    Second the query is parameterized, in this way it is a lot more clear what you are doing, avoid sql injections and problems with the correct parsing of the values.