2

Hi guys I have got a simple insert statement, I know something is missing as when I click the button to insert the data it dose not insert. any ideas?

 protected void saveyear_Click(object sender, EventArgs e)
{
    OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\ASPNetDB.mdb;Persist Security Info=True");
    OleDbDataAdapter da = new OleDbDataAdapter();

    da.InsertCommand = new OleDbCommand("INSERT INTO DVD_Infomation (Year) VALUES (@Year)", connection);
    {
        da.InsertCommand.Parameters.AddWithValue("@Year", Year.Text);
    }

    connection.Open();

        da.InsertCommand.ExecuteNonQuery();

    connection.Close();
}

2 Answers 2

5

YEAR is a reserved keyword for MS-Access Jet.
If you want to use it as name of your column you should enclose it in square brackets

da.InsertCommand = new OleDbCommand("INSERT INTO DVD_Infomation ([Year]) VALUES (@Year)", connection);
{
    da.InsertCommand.Parameters.AddWithValue("@Year", Year.Text);
}

If it is still possible, I suggest to change the name of that column. It will be annoying to stump on this error every time you try to use that column in your statements

As a side note, I would write the code above as

using(OleDbConnection connection = new OleDbConnection(.....))
using(OleDbCommand cmd = new OleDbCommand("INSERT INTO DVD_Infomation ([Year]) VALUES (@Year)", connection))
{
    cmd.Parameters.AddWithValue("@Year", Year.Text);
    connection.Open();
    cmd.ExecuteNonQuery();
}

Adding the using statement around the creation of the connection and the command will ensure a proper closing and disposing of these objects also in case of exceptions and keep your program more resource usage friendly

Sign up to request clarification or add additional context in comments.

Comments

2

Never use a Reserved word in your tables, if you can help it. Since YEAR is a Reserved word, you need to use brackets around the name. Preferrably, change the field name in your table to avoid that issue in the future. Similarly, using field names with spaces in them is also frowned upon as it, too, creates problems when referencing them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.