views:

32

answers:

1

Hello,

I have a visual C# project and i'm trying to insert data in a MS Access Database when i press a button. Here is the code:

private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                OleDbDataAdapter adapter=new OleDbDataAdapter();
                adapter.InsertCommand = new OleDbCommand();
                adapter.InsertCommand.CommandText =
                     "insert into Candidati values ('" + maskedTextBox1.Text.Trim() + "','" + textBox1.Text.Trim() + "', '" + textBox2.Text.Trim() + "', '" + textBox3.Text.Trim() + "','" + Convert.ToDouble(maskedTextBox2.Text) + "','" + Convert.ToDouble(maskedTextBox3.Text) + "')";
                con.Open();
                adapter.InsertCommand.Connection = con;
                adapter.InsertCommand.ExecuteNonQuery();
                con.Close();
                MessageBox.Show("Inregistrare adaugata cu succes!");
                maskedTextBox1.Text = null;
                maskedTextBox2.Text = null;
                maskedTextBox3.Text = null;
                textBox1.Text = null;
                textBox2.Text = null;
                textBox3.Text = null;
                maskedTextBox1.Focus();
            }
            catch (AdmitereException exc)
            {
                MessageBox.Show("A aparut o exceptie: "+exc.Message, "Eroare!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

The connection string is:

private static string connectionString;
        OleDbConnection con;
        public AddCandidati()
        {
            connectionString = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=Admitere.mdb";
            con = new OleDbConnection(connectionString);
            InitializeComponent();
        }

Where AddCandidati is the form. The data is not saved in the database, why? I have the .mdb file in the project folder.. What i'm doing wrong? I did not got any exception when i press the button..

Thanks!

A: 

Your insert command is wrong. You have to specify the names of the columns first, then you give the values for each of those columns.

INSERT INTO tablename (column1, column2, column3) VALUES ('value1', 'value2', 'value3')
ZippyV
No, there is no need to specify the columns first. I changed with connectionString = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=D:\\Admitere.mdb"; (also, copied the database in D:\) and now worked.
qwerty
@qwerty Are you saying you solved the problem? If so, please either answer and mark it or delete it.
Jay
I solved. Thanks. But not the last post was the answer..
qwerty