473,587 Members | 2,230 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

References to CurrentDb? Persistent?

I'm trying to execute an append query. I have a case that works, and
one that returns an object not set error.

THIS WORKS:

Private Sub cmdArchiveRecs_ Click()
BeginTrans
CurrentDb.Execu te "qapp_RecsNotYe tArchived", dbFailOnError
CommitTrans
End Sub

THIS DOESN'T WORK. It returns OBJECT NOT SET on dbLocal.Execute ():

Dim dbLocal As DAO.Database

Private Sub Form_Load()
Set dbLocal = CurrentDb
End Sub

Private Sub Form_Unload(Can cel As Integer)
dbLocal.Close
Set dbLocal = Nothing
End Sub

Private Sub cmdArchiveRecs_ Click()
BeginTrans
dbLocal.Execute "qapp_RecsNotYe tArchived", dbFailOnError
CommitTrans
End Sub

Why isn't "dbLocal" set for the life of the form? Of what value is
setting a reference vice always using CurrentDb?

Thanks,

-Tony M.

Jun 5 '06 #1
7 4985
I don't remember the reason anymore, but I do remember that when you use
CurrentDB you're getting a transient refefence to the DB. The way to cope
is to declare a variable of type dao.database. Then:

set db = currentdb
do stuff
do stuff
do stuff
set db = nothing

Maintaining a reference to the same instance (?) of the db pointer buys you
some things, such as being able to do a db.execute and followup with a test
on db.RecordsAffec ted.

(If your data is in SQL Server: Quite often you may prefer to define an
adodb.connectio n object and an adodb.command object, get your connection,
construct your command, and execute the command object, which moves the
processing out of Access and up to the server.)
Jun 6 '06 #2
The reason is that when VBA hits a CurrentDb, it stops what it is doing, and
flushes all the collections of all the objects in the DAO tree. It then
creates a new object, and points it to the default database, which is
typically dbEngine.Worksp aces(0).Databas e(0). Since all collections are
flushed and a new object is created, anything that depended on the existence
of the previous object is no available.

The original question was about the traps when handling transactions. There
is an example and discussion of the pitfalls in this article:
Archive: Move records to another table
at:
http://allenbrowne.com/ser-37.html

--
Allen Browne - Microsoft MVP. Perth, Western Australia.
Tips for Access users - http://allenbrowne.com/tips.html
Reply to group, rather than allenbrowne at mvps dot org.

<w_a_n_n_a_l_ l_ -@-_s_b_c_g_l_o_b_ a_l._n_e_t> wrote in message
news:df******** ***********@new ssvr27.news.pro digy.net...
I don't remember the reason anymore, but I do remember that when you use
CurrentDB you're getting a transient refefence to the DB. The way to cope
is to declare a variable of type dao.database. Then:

set db = currentdb
do stuff
do stuff
do stuff
set db = nothing

Maintaining a reference to the same instance (?) of the db pointer buys
you
some things, such as being able to do a db.execute and followup with a
test
on db.RecordsAffec ted.

(If your data is in SQL Server: Quite often you may prefer to define an
adodb.connectio n object and an adodb.command object, get your connection,
construct your command, and execute the command object, which moves the
processing out of Access and up to the server.)

Jun 6 '06 #3
"Tony M." <an************ *@navy.mil> wrote in
news:11******** **************@ j55g2000cwa.goo glegroups.com:
I'm trying to execute an append query. I have a case that works,
and one that returns an object not set error.

THIS WORKS:

Private Sub cmdArchiveRecs_ Click()
BeginTrans
CurrentDb.Execu te "qapp_RecsNotYe tArchived", dbFailOnError
CommitTrans
End Sub

THIS DOESN'T WORK. It returns OBJECT NOT SET on dbLocal.Execute ():

Dim dbLocal As DAO.Database

Private Sub Form_Load()
Set dbLocal = CurrentDb
End Sub

Private Sub Form_Unload(Can cel As Integer)
dbLocal.Close
Set dbLocal = Nothing
End Sub

Private Sub cmdArchiveRecs_ Click()
BeginTrans
dbLocal.Execute "qapp_RecsNotYe tArchived", dbFailOnError
CommitTrans
End Sub

Why isn't "dbLocal" set for the life of the form? Of what value is
setting a reference vice always using CurrentDb?


A truly persistent cached reference is much more useful. I've often
posted my code for a public function called dbLocal() that can be
used just like a public DAO.Database variable, and the code for that
is posted below after my sig. A discussion of some of the issues of
how it works is found in the thread beginning with this post:

http://groups.google.com/group/comp..../msg/9520d63d8
9decbb3

Paste the code into a public module and then you don't have to
declare a database variable anywhere in your app, or maintain a
public variable -- just use dbLocal anywhere you'd have used a
database variable initialized with CurrentDB() and forget about it.

The one thing you might want to do (though it's not strictly
necessary) is to de-initialize the variable when closing your app.
This is done by calling dbLocal with the optional argument set to
False.

--
David W. Fenton http://www.dfenton.com/
usenet at dfenton dot com http://www.dfenton.com/DFA/

Public Function dbLocal(Optiona l ysnInitialize As Boolean = True) _
As DAO.Database
' 2003/02/08 DWF added comments to explain it to myself!
' 2005/03/18 DWF changed to use Static variable instead
' uses GoTos instead of If/Then because:
' error of dbCurrent not being Nothing but dbCurrent being closed
' would (3420) would then be jumping back into the middle of an
' If/Then statement
On Error GoTo errHandler
Static dbCurrent As DAO.Database
Dim strTest As String

If Not ysnInitialize Then GoTo closeDB

retryDB:
If dbCurrent Is Nothing Then
Set dbCurrent = CurrentDb()
End If
' now that we know the db variable is not Nothing, test
' if it's Open
strTest = dbCurrent.Name

exitRoutine:
Set dbLocal = dbCurrent
Exit Function

closeDB:
If Not (dbCurrent Is Nothing) Then
'dbCurrent.clos e
Set dbCurrent = Nothing
End If
GoTo exitRoutine

errHandler:
Select Case Err.Number
Case 3420 ' Object invalid or no longer set.
Set dbCurrent = Nothing
If ysnInitialize Then
Resume retryDB
Else
Resume closeDB
End If
Case Else
MsgBox Err.Number & ": " & Err.Description , vbExclamation, _
"Error in Public Function dbLocal()"
Resume exitRoutine
End Select
End Function
Jun 6 '06 #4
No one pointed out that my problem seems to be the opposite of what's
being recommended. What should work isn't, and what does work is not
the recommended approach, right? Allen, are you saying that it has
something to do with the transaction I wrapped around the execute
statement? Your link below does not resolve for me.

Thanks,

-Tony M.

Allen Browne wrote:
The reason is that when VBA hits a CurrentDb, it stops what it is doing, and
flushes all the collections of all the objects in the DAO tree. It then
creates a new object, and points it to the default database, which is
typically dbEngine.Worksp aces(0).Databas e(0). Since all collections are
flushed and a new object is created, anything that depended on the existence
of the previous object is no available.

The original question was about the traps when handling transactions. There
is an example and discussion of the pitfalls in this article:
Archive: Move records to another table
at:
http://allenbrowne.com/ser-37.html

--
Allen Browne - Microsoft MVP. Perth, Western Australia.
Tips for Access users - http://allenbrowne.com/tips.html
Reply to group, rather than allenbrowne at mvps dot org.

<w_a_n_n_a_l_ l_ -@-_s_b_c_g_l_o_b_ a_l._n_e_t> wrote in message
news:df******** ***********@new ssvr27.news.pro digy.net...
I don't remember the reason anymore, but I do remember that when you use
CurrentDB you're getting a transient refefence to the DB. The way to cope
is to declare a variable of type dao.database. Then:

set db = currentdb
do stuff
do stuff
do stuff
set db = nothing

Maintaining a reference to the same instance (?) of the db pointer buys
you
some things, such as being able to do a db.execute and followup with a
test
on db.RecordsAffec ted.

(If your data is in SQL Server: Quite often you may prefer to define an
adodb.connectio n object and an adodb.command object, get your connection,
construct your command, and execute the command object, which moves the
processing out of Access and up to the server.)


Jun 6 '06 #5
Okay, you want us to evaluate what's happening with your code.

1. The first line of your cmdArchiveRecs is an unqualified BeginTrans.
Are you beginning a transaction on the dbEngine object?
On the default workspace object?
Or do you have ADO as a higher priority reference, so this is actualy an ADO
transaction?

2. Your form_Unload *closes* the local database, which is always open. (You
did not open this; you merely assigned a variable to it.) Access will
automatically open it again, but there can be side effects for this kind of
thing.

3. I am not clear what's going on with your unqualified BeginTrans, and lack
of other info (such as whether you may have Reset the project at some point
since the form opened), but the error message suggests that your dbLocal
variable has been destroyed at some point. The default database is dependent
on dbEngine(0) which in turn is dependent on dbEngine, so the presence of a
transaction on either of those will affect the object that depended on them.

--
Allen Browne - Microsoft MVP. Perth, Western Australia.
Tips for Access users - http://allenbrowne.com/tips.html
Reply to group, rather than allenbrowne at mvps dot org.

"Tony M." <an************ *@navy.mil> wrote in message
news:11******** **************@ u72g2000cwu.goo glegroups.com.. .
No one pointed out that my problem seems to be the opposite of what's
being recommended. What should work isn't, and what does work is not
the recommended approach, right? Allen, are you saying that it has
something to do with the transaction I wrapped around the execute
statement? Your link below does not resolve for me.

Thanks,

-Tony M.

Allen Browne wrote:
The reason is that when VBA hits a CurrentDb, it stops what it is doing,
and
flushes all the collections of all the objects in the DAO tree. It then
creates a new object, and points it to the default database, which is
typically dbEngine.Worksp aces(0).Databas e(0). Since all collections are
flushed and a new object is created, anything that depended on the
existence
of the previous object is no available.

The original question was about the traps when handling transactions.
There
is an example and discussion of the pitfalls in this article:
Archive: Move records to another table
at:
http://allenbrowne.com/ser-37.html

<w_a_n_n_a_l_ l_ -@-_s_b_c_g_l_o_b_ a_l._n_e_t> wrote in message
news:df******** ***********@new ssvr27.news.pro digy.net...
>I don't remember the reason anymore, but I do remember that when you use
> CurrentDB you're getting a transient refefence to the DB. The way to
> cope
> is to declare a variable of type dao.database. Then:
>
> set db = currentdb
> do stuff
> do stuff
> do stuff
> set db = nothing
>
> Maintaining a reference to the same instance (?) of the db pointer buys
> you
> some things, such as being able to do a db.execute and followup with a
> test
> on db.RecordsAffec ted.
>
> (If your data is in SQL Server: Quite often you may prefer to define
> an
> adodb.connectio n object and an adodb.command object, get your
> connection,
> construct your command, and execute the command object, which moves the
> processing out of Access and up to the server.)

Jun 6 '06 #6
Been a long time since I've done transactions in Access, but the example in
help these days (which matches my memory of how I was doing it), shows use
of BeginTrans et al off the Workspace object.

The general approach is this:

Public Function testws()

Dim ws As Workspace
Set ws = DBEngine.Worksp aces(0)

On Error GoTo Generic_Error
'prep work here

ws.BeginTrans
On Error GoTo RollMeBack

'insert
'update
'delete
'whatever

'finished, commit
ws.CommitTrans
Exit_testws:
Set ws = Nothing

Generic_Error:
MsgBox err.Description
Resume Exit_testws

RollMeBack:
MsgBox err.Description , vbCritical, "Rolling Back After Error"
ws.Rollback
Resume Exit_testws

End Function
You can get much more detailed and even nest transactions several layers
deep, though I can't remember why on earth I thought I needed to do that any
more.

Does this help?
Jun 6 '06 #7
Add "Exit Function" after "Set ws = nothing
Jun 6 '06 #8

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

Similar topics

3
2782
by: Randell D. | last post by:
Folks, I currently connect to my db with PHP code that uses non-persistent connections. I've read that persistent connections can help performance since a connection to the db will use an existing unused connection. If my system was to go through a busy period whereby I seen an extra 50% or more activity for ten minutes or so, would the...
0
2481
by: obhayes | last post by:
Hi All, Im using classic ASP (3.0) and I have a web farm with 2 webservers (webserver A and webserver B, both windows server 2003). I do not want to store any client specific information on the webserver (therefore do not intend to use the session object- as you cannot gaurantee which server the user will go to). I want to store a small value...
1
4598
by: brad | last post by:
Hi, Im using classic ASP (3.0) and I have a web farm with 2 webservers (webserver A and webserver B, both windows server 2003). I do not want to store any client specific information on the webserver (therefore do not intend to use the session object- as you cannot gaurantee which server the user will go to). I want to store a small value...
4
2448
by: M?rio Amado Alves | last post by:
Will you help an outsider trying to trace the current state of persistent object technology? "I expect that there will be persistent object stores with STL-conforming interfaces fitting into the STL framework within the next year." --Alexander Stepanov, 1995 Has this happened? (In 1996 or another year.)
25
6187
by: Steve Jorgensen | last post by:
Yup, Steve's full of tips, but hey, it makes him feel important, right? Ok, here goes. I've been trying to improve encapsulation by putting code in the same object as the stuff it affects, so I rarely refer to a subform ir parent form's controls or records from the other form. Instead, I call a procedure in that form that does the job. ...
1
4343
by: Eric Lindsay | last post by:
I am trying to understand the differences between and uses of persistent, default and alternate styles. I have read http://www.w3.org/TR/REC-html40/present/styles.html section 14.3.2 on specifying external style sheets in link using combinations of rel and using or not using the title attribute. I think I sort of understand rel="alternate...
0
1202
by: Anubhav Jain | last post by:
Hi, I am creating a visual studio template in VS.Net 2005. It contains webproject or website as one of the project. I am successfully abele to add the references into the other project. using this following lines of code. foreach (Project proj in projs){ if (!proj.Name.Contains("BusinessObjects") && !proj.Name.Contains("http"))
3
4287
by: sanchita | last post by:
Hello everyone, I didn't get any response in "Security" forum hence posting here again. I am having problem with persistent cookies. Even after setting "CreatePersistentCookie" to true in "FormsAuthentication.SetAuthCookie" I'm being logged out after the specifed timeout provided in "forms" element of web.config. I read somewhere that...
9
2670
by: mel | last post by:
Hi all, I need a persistent TCP connection with my web server over page reloads. This means that, even if the user goes to a different page (in my domain), I want to keep a TCP connection live. I know I can do something similar with globalStorage in FF, window.name & userData on IE, but those storages only hold strings.
0
8339
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...
1
7967
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8220
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...
0
5392
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3840
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...
0
3872
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2347
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1452
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1185
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...

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.