473,695 Members | 2,389 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Access, OleDb, Insert or Update

I'm using OleDb to connect with an Access Database. I have anywhere from
10 to over 100 records that I need to either INSERT if the PK doesn't
exist or UPDATE if the PK does exist, all in a single transaction. Does
anyone have an SQL statement I can throw at it that would accomplish
this?

If I can't figure out how to do it, I'm going to have to send two
discreet SQL commands for each record which will take infinitely longer
than a single transaction.

*** Sent via Developersdex http://www.developersdex.com ***
Dec 24 '07 #1
13 8870
Terry Olsen wrote:
I'm using OleDb to connect with an Access Database. I have anywhere from
10 to over 100 records that I need to either INSERT if the PK doesn't
exist or UPDATE if the PK does exist, all in a single transaction. Does
anyone have an SQL statement I can throw at it that would accomplish
this?

If I can't figure out how to do it, I'm going to have to send two
discreet SQL commands for each record which will take infinitely longer
than a single transaction.

*** Sent via Developersdex http://www.developersdex.com ***
With Jet, I don't think you can fire off one statement to do that. I
think you'd need at least two - but there shouldn't be any need to fire
it per each record.

Say table a and b with identical structure, I think you'd first do the
update where the PK exists

UPDATE a INNER JOIN b ON a.id = b.id
SET
a.field1 = b.field1
a.field2 = b.field2
.....

then try the insert

INSERT INTO a
SELECT *
FROM b
WHERE Not Exists (
SELECT id
FROM a
WHERE a.id = b.id)

Technically You're not connecting to an Access database, as such beast
doesn't really exist ;-)

You're connecting to a Jet database, which also happens to be the
default database of Access. But Access can also be used as front end for
other platforms.

I don't know much about the .Net world, but aren't there supposed to be
some automatic update/insert thingies in connection with the data
adapter or datatable (commandbuilder ?)? Perhaps an inquiry to a NG
dedicated to the technology you're using might give more precise
answers?

--
Roy-Vidar
Dec 25 '07 #2
Greetings,

.Net is tricking you a little bit. You can combine a
select/Insert/Update/Delete command in a single dataAdapter object. So
you really have 4 separate commands combined into one when you first
create the dataAdapter object. You have to declare each command
individually, then when you fill a dataset with data from a database
table (Access, MS Sql Server, Oracle...) all you have to do is edit your
in memory dataset datatable and the commands you declared will take care
of the rest automatically.

Note: I would steer clear of the command builder object. It creates
generic commands that may not necessarily suit your needs. Here is how
you declare all your command in one shot (at the Form Level):

Imports System.Data
Imports System.Data.Ole DB

Dim da As OleDBDataAdapte r, conn As OleDBConnection
Dim ds As DataSet

Private Sub Form1_Load(...) ...
ds = New DataSet
conn = New OleDBConnection
conn.Connection String = "provider=micro soft.jet.oledb. 4.0; Data Source =
db2test.mdb"
da = New OleDBDataAdapte r
da.SelectComman d = New OleDBCommand
da.SelectComman d.Connection = conn
da.InsertComman d = New OleDBCommand
da.InsertComman d.Connection = conn
da.UpdateComman d = New OleDBCommand
da.UpDateComman d.Connection = conn

da.InsertComman d.CommandText = "Insert Into Table1(FName, LName, Phone)
Select @FName, @LName, @Phone"
da.InsertComman d.Parameters.Ad d("@Fname", OleDBType.Varch ar, 50,
"FName")
da.InsertComman d.Parameters.Ad d("@LName", OleDBType.Varch ar, 50,
"LName")
da.InsertComman d.Parameters.Ad d("@Phone", OleDBType.Varch ar, 50,
"Phone")

'--do the same for the UPdate Command

da.SelectComman d.CommandText = "Select * from Table1"
da.Fill(ds, "tbl1") '--tbl1 gets created automatically inside ds when
calling da.Fill

'--Note: if you are entering/editing data through datagridview control,
then you will have to loop through your dataset table to copy the
entries/edits from the datagridview to the dataset table and then call

da.Update(ds, "tbl1")

the da.Update call will automatically invoke either/and/or the
Insert/Update commands. da.Fill only applies to the Select command.
So, if you are entering data directly into your dataset table from
textboxes, then you don't need to worry about making sure that
entries/edits are already in the dataset table:

Private Sub btnAdd_Click(.. .)handles btn1.Click
Dim dr As DataRow
dr = ds.Tables("tbl1 ").NewRow
dr("FName") = txtFName.text
dr("LName") = txtLName.Text
dr("Phone") = txtPhone.Text
ds.Tables("tbl1 ").Rows.Add (dr)
da.Update(ds, "tbl1")
End Sub

Another Note: .Net may seem a little bit on the busy side or complex -
i.e. for Access. Where ADO.Net is real nice is when you are dealing
with large tables on a sql server DB. Actually, if you have to upload
data from a bunch of Access MDB's to the sql server, ADO.Net is real
nice for that too. It is a straight forward pull and push. You use the
da.Fill command to pull the data from Access to your memory table
da.Fill(ds, "tbl1") and then use the dataTable.Creat eReader property of
the memory table to push the data straight to the sql server table. No
data looping involved (I had to write a routine to import data from 50
mdb's in one shot to a sql server db table - it was a snap with
ADO.Net). I did have to set up a loop to import the data from each MDB
to my memory table (all the tables were the same structure for each
mdb). Then I pushed the data in my memory table to the sql server in
one shot:

Dim reader As DataTableReader = dsSql.tblImport .CreateDataRead er
dsOle.Tables("t bl1").Load(read er, LoadOption.Upse rt)
daSql.Update(ds Sql, "tblSql")

Note: have to create the sqlInsert, sqlUpdate commands and all the
parameters for this to work. And if you have at least 2gigs of memory
and at least a 2.8 gig processor, this will upload 500,000 records in a
matter of seconds (the hardware is the catch with .Net).

Rich

*** Sent via Developersdex http://www.developersdex.com ***
Dec 26 '07 #3
Thanks for the help. I'll try the DataAdapter approach. I was just
iterating through the DataTable myself.

Anyway, I'm forced to use an Access file because I was using SQL Express
but I received a "cease & desist" email from corporate. They detected my
SQL instance and told me it was unauthroized and needed to be
uninstalled. So now i'm attempting to salvage our very useful app by
using an MDB file instead.

The file is going to be staged in a shared directory and several people
use the app. So i'm trying to make each connection to the MDB file as
quick as possible to avoid simultaneous hits.

*** Sent via Developersdex http://www.developersdex.com ***
Dec 27 '07 #4
Sorry to hear about the Cease and Desist thing. I have sort of been
there (in a way). If you have to stay with Access, I would use Access
as the front and back end -- unless you just want to stay in practice
with .Net. Otherwise, it might be a little bit overkill. Although, if
you are using VS2005, one nice feature is deploying stuff - you have the
Click Once feature which works nicely with C# 2005 or VB2005 for
deploying your front end and keep an Access backend on the server.

Good Luck!

Rich

*** Sent via Developersdex http://www.developersdex.com ***
Dec 27 '07 #5
Terry Olsen <to******@hotma il.comwrote:
>Anyway, I'm forced to use an Access file because I was using SQL Express
but I received a "cease & desist" email from corporate. They detected my
SQL instance and told me it was unauthroized and needed to be
uninstalled.
Morons.
>The file is going to be staged in a shared directory and several people
use the app. So i'm trying to make each connection to the MDB file as
quick as possible to avoid simultaneous hits.
How many users entering/updating data?

Tony
--
Tony Toews, Microsoft Access MVP
Please respond only in the newsgroups so that others can
read the entire thread of messages.
Microsoft Access Links, Hints, Tips & Accounting Systems at
http://www.granite.ab.ca/accsmstr.htm
Tony's Microsoft Access Blog - http://msmvps.com/blogs/access/
Dec 28 '07 #6
Well, I'll have about 20 people using the app and updating the data. I
don't know too much about Access itself, is it possible for more than
one person to have an MDB file open simultaneously? And not to mention I
expect the database to be about 20MB. Opening that up across the network
in Access would be painfully slow.

*** Sent via Developersdex http://www.developersdex.com ***
Dec 28 '07 #7
There's about 20 people in our work group that will be updating the
data. They are all IT Technicians and the database keeps all the PC
Information (we have around 2000 PC's in our district). The database is
often used because in addition to the PC audit info, it's also used for
our "Netop Phonebook" and disaster recovery information (where is the
current ghost image located for each pc?). It's also used for our
WakeOnLan requirements. So it's a pretty busy database. Shame we had to
lose the SQL db.

*** Sent via Developersdex http://www.developersdex.com ***
Dec 28 '07 #8
Terry Olsen <to******@hotma il.comwrote:
>Well, I'll have about 20 people using the app and updating the data. I
don't know too much about Access itself, is it possible for more than
one person to have an MDB file open simultaneously?
20 users won't be a problem so long as the network hardware and softare is in good
shape.

You want to split the MDB into a Front End MDB containing the queries, forms,
reports, macros and modules with just the tables and relationships in the Back End
MDB. The FE is copied to each network users computer. The FE MDB is linked to the
tables in the back end MDB which resides on a server. You make updates to the FE
MDB and distribute them to the users, likely as an MDE.

See the "Splitting your app into a front end and back end Tips" page at
http://www.granite.ab.ca/access/splitapp/ for more info. See the Auto FE Updater
downloads page http://www.granite.ab.ca/access/autofe.htm to make this relatively
painless.. The utility also supports Terminal Server/Citrix quite nicely.
>?And not to mention I
expect the database to be about 20MB. Opening that up across the network
in Access would be painfully slow.
Um, why would a 20 Mb backend database be slow? Despite urban, ok in this case, IT
folklore, WHICH IS TOTALLY WRONG, Access does not pull down the entire database or
even entire tables unless your selection or sorting criteria isn't indexed. Now in a
WAN situation Access isn't very good. Performance is terrible and chances of
corruption are high. But in a 100 mbps LAN performance is just fine.

Tony
--
Tony Toews, Microsoft Access MVP
Please respond only in the newsgroups so that others can
read the entire thread of messages.
Microsoft Access Links, Hints, Tips & Accounting Systems at
http://www.granite.ab.ca/accsmstr.htm
Tony's Microsoft Access Blog - http://msmvps.com/blogs/access/
Dec 28 '07 #9
Terry Olsen <to******@hotma il.comwrote:
>There's about 20 people in our work group that will be updating the
data. They are all IT Technicians and the database keeps all the PC
Information (we have around 2000 PC's in our district). The database is
often used because in addition to the PC audit info, it's also used for
our "Netop Phonebook" and disaster recovery information (where is the
current ghost image located for each pc?). It's also used for our
WakeOnLan requirements. So it's a pretty busy database. Shame we had to
lose the SQL db.
See my reply to your other posting.

Tony
--
Tony Toews, Microsoft Access MVP
Please respond only in the newsgroups so that others can
read the entire thread of messages.
Microsoft Access Links, Hints, Tips & Accounting Systems at
http://www.granite.ab.ca/accsmstr.htm
Tony's Microsoft Access Blog - http://msmvps.com/blogs/access/
Dec 28 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
17011
by: Philip Boonzaaier | last post by:
I want to be able to generate SQL statements that will go through a list of data, effectively row by row, enquire on the database if this exists in the selected table- If it exists, then the colums must be UPDATED, if not, they must be INSERTED. Logically then, I would like to SELECT * FROM <TABLE> WHERE ....<Values entered here>, and then IF FOUND UPDATE <TABLE> SET .... <Values entered here> ELSE INSERT INTO <TABLE> VALUES <Values...
3
3443
by: Shapper | last post by:
Hello, I have created 3 functions to insert, update and delete an Access database record. The Insert and the Delete code are working fine. The update is not. I checked and my database has all the necessary records in it when testing it. I get the error "No value given for one or more required parameters." when I try to update the database. Can you tell me what am I doing wrong?
9
2876
by: DraguVaso | last post by:
Hi, I'm writing a VB.NET application who has to insert/update and delete a whole bunch of records from a File into a Sql Server Database. But I want to be able to knwo the 'result' of my ctions. for exemple: - after an INSERT: knowing if this happened well or not - after an UPDATE: knowing wich number of records were updated (or if there were records udpated or not)
8
5396
by: erin.sebastian | last post by:
Hi all, I have a really silly problem that i can't find the answer too. I am working with VB.NET and i am trying to insert a new record into my access database (pretty easy right?) well i am getting a syntax error in my SQL statement and nothing i do will correct it. It looks FINE to me, can anyone help me out?? Thanks so much in advance, here is the code i am using Dim cn As OleDbConnection Dim cmd As OleDbCommand
6
2610
by: Tom Allison | last post by:
I seemed to remember being able to do this but I can't find the docs. Can I run a sql query to insert new or update existing rows in one query? Otherwise I have to run a select query to see if it's there and then another one to update/insert. What I'm trying to do is create a counter for each key, insert a value of 1 or increment the value by 1 and then set another specific row (where key = $key) to always increment by 1.
23
4055
by: Darin | last post by:
Since there is no 64-bit Jet (MS Access) OLEDB driver, what is the recommended solution for this delimma. Our application uses SQL Server as the daatabase engine, but we have about 5 meg of static data stored in an Access database. We chose that because it is easy to read, and can be password protected. Since Microsoft doesn't have a 64-bit OLD to Access, the application has to be set to run in 100% 32-bit mode to get it to run. This...
11
3142
by: cooperkuo | last post by:
Dear all, I have a question about ADO in the subform. I know how to use ADO to insert/update/select data into the sigin form, but wehn I try to do it in the form with subform((Datasheet). I don't have any idea how to insert/update/select the recordset data into the subform(Datasheet), especially insert/update. Would someone can give me a idea or sample code to me? Appreciate your help. OS: windows XP +SP2+ Access 2003+SP2 Database: MS...
0
2705
by: kumardharanik | last post by:
Hi Friends, The below code is a sample code for insert, update and delete using datagrid but i need to convert the entire code for datagridview.. Plsss help me.. using System; using System.Drawing; using System.Collections; using System.ComponentModel;
7
7620
by: ndhvu | last post by:
Tables: Buy_Header and Buy_Detail. - Buy_Header: info. of each buy (buy_id(PK, auto number), date, shop, bought_by, ...) - Buy_Detail: info. of each item from each buy (buy_detail_id(PK, auto number), buy_id, item_name, price, quantity,...) Target: - Make a main-form of table with sub-form of table to insert/update records for both tables. Each form of each and the sub-form can have many records of . - When update, you can add more...
0
8631
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8572
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9115
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8984
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8825
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7661
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6491
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4340
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
1976
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.