Click here to Skip to main content
15,892,737 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using the following code to insert form data into MSAcess2003 database:
private void button1_Click(object sender, EventArgs e)
       {
           try
           {
               OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= |DataDirectory|/Schooldb.mdb");
               conn.Open();
               OleDbCommand cmd = new OleDbCommand("insert into StudentReg(Class,Current_date)values('"+comboBox1.SelectedItem+"','"+dateTimePicker1.Text+"')", conn);

               cmd.CommandType = CommandType.Text;
               cmd.ExecuteNonQuery();
               MessageBox.Show("Data is inserted!!");
           }
           catch(Exception ex)
           {
               MessageBox.Show(ex.ToString());

           }


       }






but i am getting the Error:
Syntex Error in (insert into)
Posted

Firstly, don't do it like that - use parametrized queries instead.
Secondly, Don't use SelectedItem unless you know it is a string,
Thirdly, Don't convert dates unnecessarily:
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= |DataDirectory|/Schooldb.mdb");
conn.Open();
C#
OleDbCommand cmd = new OleDbCommand("INSERT INTO StudentReg (Class, Current_date) VALUES (@CL, @CD)", conn);
cmd.Parameters.AddWithValue("@CL", comboBox1.SelectedText);
cmd.Parameters.AddWithValue("@CD", dateTimePicker1.Value);
cmd.ExecuteNonQuery();

Fourthly, clean up behind yourself! Connnections and COmmands are valuablke resources - you should be Closing and Dosposing:

C#
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= |DataDirectory|/Schooldb.mdb"))
   {
   conn.Open();
   using (OleDbCommand cmd = new OleDbCommand("INSERT INTO StudentReg (Class, Current_date) VALUES (@CL, @CD)", conn))
      {
      cmd.Parameters.AddWithValue("@CL", comboBox1.SelectedText);
      cmd.Parameters.AddWithValue("@CD", dateTimePicker1.Value);
      cmd.ExecuteNonQuery();
      }
   }
 
Share this answer
 
Hi,
I think Error Cause Because u use keyword Class in ur query Change ur column name and Try It
Best Luck
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900