Click here to Skip to main content
15,890,579 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to use MS Access as database for my C# windows form application.I have used OleDb driver for connecting MS Access. I am able to select the records from the MS Access using OleDbConnection and ExecuteReader.But I am unable to insert,update and delete records. My code is as follows:

OleDbConnection con=new OleDbConnection(strCon);
        try
        {
        con.Open();
        OleDbCommand com = new OleDbCommand("INSERT INTO DPMaster(DPID,DPName,ClientID,ClientName) VALUES('53','we','41','aw')", con);

        int a=com.ExecuteNonQuery();

        //OleDbCommand com = new OleDbCommand("SELECT * FROM DPMaster", con);
        //OleDbDataReader dr = com.ExecuteReader();
        //while (dr.Read())
        //{
        //    MessageBox.Show(dr[2].ToString());
        //}
        MessageBox.Show(a.ToString());
        }
        catch
        {
            MessageBox.Show("cannot");
        }


If I execute the commented block the application works.But the insert block doesnt works.Why I am unable to insert/update/delete the records into database?
My Connection String is as follows:

string strCon="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=xyz.mdb;Persist Security Info=True";
Posted
Updated 24-Dec-10 4:04am
v2
Comments
JOAT-MON 24-Dec-10 9:25am    
1. What are the data types of the columns you are inserting?
2. Are any of your columns auto-numbered?
3. Are there more than the 4 columns in the table?
Hiren solanki 24-Dec-10 10:04am    
OP solved himself.

OleDbCommand com = new OleDbCommand("INSERT INTO DPMaster(DPID,DPName,ClientID,ClientName) VALUES('53','we','41','aw')", con);


I am not finding anything that causing error, But the exactly error statement can clarify the thing further, So please post it here.

The way you're using insert query is a very bad practice, Use Parameterized Query instead.
 
Share this answer
 
Comments
abi1988 24-Dec-10 9:49am    
Actually no error was coming while executing this code.The data were not inserted into the database, that was only the problem.

I will be using parameterized query only..but for sample i have posted this query here.
I got solution for this problem.

I was keeping the database inside the project(solution) itself.But when I kept the database out of the project as per one's suggestion, the above code works fine.

I don't know what is the relation for this problem with the location of the database file.But now problem gets solved.

If any one has idea about why the code didn't worked if we have the db inside the solution,plz post it.

Thanks in advance.
 
Share this answer
 
v3
Comments
Hiren solanki 24-Dec-10 10:03am    
Great it worked.

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