Search code examples
c#ms-accessoledb

Adding data to a database using C#


I'm currently trying to use C# to add data into an access database (saved as mdb) here is my current code:

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        private OleDbConnection bookConn;
        private OleDbCommand oleDbCmd = new OleDbCommand();
        private String connParam = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Alex\Desktop\Project\example.mdb;Persist Security Info=False";


        public Form1()
        {
            bookConn = new OleDbConnection(connParam);
            InitializeComponent();
        }

        public void add()
        {
            try
            {
                bookConn.Open();
                oleDbCmd.Connection = bookConn;
                oleDbCmd.CommandText = "INSERT INTO Student (StudentID, Module) VALUES ('"+ this.textBox1.Text +"','"+ this.textBox2.Text +"');";
                oleDbCmd.CommandType = CommandType.Text;
                int temp = oleDbCmd.ExecuteNonQuery();
                if (temp > 0)
                {
                    MessageBox.Show("Added");
                }
                else
                {
                    MessageBox.Show("Failed");
                }
                bookConn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            add();
        }


    }
}

When i run this code i get the error message : Syntax error in INSERT INTO statement.

I can't work out what i'm doing wrong when i compare to other examples it seems to be set up right.

Any help to solve this problem would be greatly appreciated.


Solution

  • Module is a reserved word. Rename the field if possible/practical. If you must keep that as the field name, enclose it in square brackets in your INSERT statement.

    oleDbCmd.CommandText = "INSERT INTO Student (StudentID, [Module]) VALUES ('"+ this.textBox1.Text +"','"+ this.textBox2.Text +"');";