Click here to Skip to main content
15,905,323 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to insert data from c sharp to ms access..
i tried but i yet some errors.. can anyone help me. this is my code
<pre lang="cs">private void button1_Click(object sender, EventArgs e)
       {

           try
           {
 OleDbConnection con = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='C:/Documents and Settings/Spartanspears/My Documents/Visual Studio 2005/Projects/room/ms access/Room_mgmt.mdb'");
                con.Open();

               // OleDbCommand comm = new OleDbCommand("Insert into individual_expenses(karthi,amount,deta) VALUES('"+cmbBox1.Text+"','"+txtBox1.Text+"','"+txtBox2.Text+"','"+txtBox3.Text+"')");
                OleDbCommand comm = new OleDbCommand("Insert into individual_expenses(karthi,amount,deta) VALUES(' name',' gjhjhgjh','55',' 44')");
                comm.ExecuteNonQuery();
            } 
            catch(Exception ex)
            {
                    MessageBox.Show(ex.ToString());
                }
            }



I got this error "execute nonquery: connection property is initialized"
Posted

An example:

using System.Data.OleDb;

OleDbConnection myConnection = new OleDbConnection();
OleDbCommand myCommand = new OleDbCommand();
string connectionString = ConfigurationManager.ConnectionStrings["DataBase"].ConnectionString;
string query = "";
myConnection.ConnectionString = connectionString;
myConnection.Open();
myCommand.Connection = myConnection;

query = "insert into Solution values (" + problems.ID + "," + problems.UserId + "," + problems.ProblemId + "," + problems.ContestId + "," + problems.ResultId + ",'" + problems.time + "','" + problems.FileName + "'," + problems.RequireTime + ");";
myCommand.CommandText = query;
myCommand.ExecuteNonQuery();
myConnection.Close();
 
Share this answer
 
Have a look at your query.

You are inserting 4 Values into 3 Columns.

Also, the command object does not know which connection to use, so you need to append the connection object to the command object. e.g.
command = new OleDbCommand("some command text", connection)

See this article for a step by step;
http://www.codeproject.com/KB/database/simpledbreadwrite.asp[^]
 
Share this answer
 
v2
You might also go for OpenRowSet transact SQL to do this :

http://msdn.microsoft.com/en-us/library/ms190312.aspx[^]

:rose:
 
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