Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Writing data to an Access database

Status
Not open for further replies.

Guggly

Programmer
Jan 18, 2004
110
US
This is probably a real dumb question, but I can't seem to figure out how to actually write data to an Access database I'm using. I can read the data fine using the following code, where QuerySQL is an SQL Select Statement.

Code:
If objConn.State.Equals(ConnectionState.Closed) Then OpenDatabase()

objAdapter = New OleDbDataAdapter(QuerySQL, objConn)

objDataSet.Tables.Add("tblMain")

objAdapter.Fill(objDataSet.Tables("tblMain"))

I can read the data fine and even write to it by doing something like this:

Code:
objDataSet.Tables("tblMain").Rows(0).Item(0) = 1

When I run the .AcceptChanges method, everything seems to work fine, but it's not actually writing to the underlying database. What do I need to do in order to actually write the data?

Thanks! -- Mike
 
You'll need to create an UpdateCommand, InsertCommand, and DeleteCommand for objAdapter and then call

objAdapter.Update(objDataSet.Tables("tblMain"))

Don't worry about calling AcceptChanges, the DataAdapter does this when you call Update.
 
You can also use the CommandBuilder object which means you won't have to spend time building parameters to pass back to the database
Keep in mind though:
1) To use the CommandBuilder, one of the columns in the Select statement must be a primary key column
2) Don't create and open the connection object yourself, Let the dataadapter do this for you. I've come across an issue ('by design' no doubt)where the data won't be updated in the database if you explicitly create new connection objects in seperate methods

There's a MS example here


but it's quite basic and doesn't change data values in seperate methods which would be the case in most scenarios (eg load data to datagrid, user changes value, clicks update)
 
Don't create and open the connection object yourself

just to elaborate as I didn't explain this too well. Create a modular connection and instantiate it ONCE in the the method that retrieves the data...but don't use it to open the connection...and don't instantiate it anywhere else
 
Thanks dalchri and jubble. Between your two suggestions I managed to figure something out and thus far it seems to be working :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top