Solved

CurrentProject.Connection.Execute(strSQL) immediately produces failed connection error

Posted on 2003-11-03
15
1,288 Views
Last Modified: 2006-11-17
I have created a SQL statement using code that I want to run using Set 'variable' = currentproject.connection.execute(strSQL).

In case, I immediately receive the error "run-time error '-2147467259 (800004005)': Method 'Execute of object '_connection' failed.

A similar line of code works in this module fine and if I cut and paste the strSQL statement from the debug window to a query, the query runs fine.  

I'm a little lost as to what I might need to do...here is the code.  The line that produces the error is near the bottom and marked.  Any insights would be greatly appreciated.

Michael


Private Sub cmdPunch1_Click()

Dim intSubID, intCoderID, intRecordCount, intKeyCount As Integer
Dim strTable, strList, strWhere, strSQLcheck, strSQLKey As String

Dim varItems(), varCheckKeys(), varKey(), varCheckData() As Variant
Dim rstCheckKeys, rsttest, rstCheckData, rstAddKeys As ADODB.Recordset


    intSubID = Me!lstSubID.Column(0)
    intCoderID = Me!lstCoderID.Column(0)
    strTable = "ftbl" & Me!lstFirst.Column(0)
    strForm = "ffrm" & Me!lstFirst.Column(0)
       
           
'Debug.Print intSubID, intCoderID, strTable
   
'Step 1: determine if ID is the only primary key

  strSQLKey = "SELECT tblPrimaryKeyNames.KeyName" & vbCrLf
  strSQLKey = strSQLKey & "        FROM tblPrimaryKeyNames" & vbCrLf
  strSQLKey = strSQLKey & "       WHERE (((tblPrimaryKeyNames.TableName)=" & """" & strTable & """" & "))" & vbCrLf
  strSQLKey = strSQLKey & "    GROUP BY tblPrimaryKeyNames.KeyName" & vbCrLf
  strSQLKey = strSQLKey & "      HAVING (((tblPrimaryKeyNames.KeyName)<>""ID""));"

  Debug.Print strSQLKey
   
---------SIMILAR LINE OF CODE RUNS FINE ------
  Set rstAddKeys = CurrentProject.Connection.Execute(strSQLKey)
---------SIMILAR LINE OF CODE RUNS FINE

  varCheckKeys() = rstAddKeys.GetRows
  intRecordCount = UBound(varCheckKeys, 2)
  rstAddKeys.Close
 
 
  If intRecordCount > 0 Then
        'Step 2: If more than one primary key, then use inputbox to get values for them
                'add key names to array
        ReDim varKey(0, intRecordCount)
             
        For a = 0 To intRecordCount
            varKey(0, a) = inputbox(varCheckKeys(0, a), "Enter the value for:")
        Next
       
       
        'SELECT ftblDataEntryTest.ID, ftblDataEntryTest.Relative, ftblDataEntryTest.Battery
        'FROM ftblDataEntryTest
        'WHERE (((ftblDataEntryTest.ID)=1) AND ((ftblDataEntryTest.Relative)="uncle")
        'AND ((ftblDataEntryTest.Battery)="first"));

       
        strList = strTable & ".ID, "
        strWhere = strTable & ".ID)=" & intSubID & ") AND (("
               
        For x = 0 To intRecordCount
            If IsNull(varCheckKeys(0, x)) = False Then
                strList = strList & strTable & "." & varCheckKeys(0, x) & ", "
                strWhere = strWhere & strTable & "." & varCheckKeys(0, x) & ")= " & varKey(0, x) & ") AND (("
            Else
            End If
        Next
        strList = Left$(strList, Len(strList) - 2)
        strWhere = Left$(strWhere, Len(strWhere) - 7)
       
       
  Else
        strList = strTable & ".ID"
        strWhere = strTable & ".ID)=" & intSubID & ")"
                     
  End If
 

'Step 3: Create StrSQL based on strList and strWhere key values

        strSQLcheck = "SELECT " & strList & " FROM " & strTable & vbCrLf
        strSQLcheck = strSQLcheck & "  WHERE ((" & strWhere & ";"
       
        Debug.Print strSQLcheck
 

'Step 4: Determine if a record for these key values already exists

------------ ERROR PRODUCED HERE ---------  
    Set rstCheckData = CurrentProject.Connection.Execute(strSQLcheck)
-------------ERROR PRODUCED HERE----------

    If rstCheckData.RecordCount > 1 Then
        MsgBox "Data for this subject already exists in this table.  Go to the Edit Data area instead"
    Else

'Step 5: If new, then open form and pass values
 
   
        varItems = adhPutItem(varItems, "SubID", intSubID)
        varItems = adhPutItem(varItems, "CoderID", intCoderID)
             
        DoCmd.OpenForm strForm, , , , , , OpenArgs:=varItems
    End If

   
End Sub
0
Comment
Question by:pansophy
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
15 Comments
 
LVL 9

Expert Comment

by:svenkarlsen
ID: 9674470
It's a bit complex, but it looks to me like you miss some closing right parenthesis for one of the possible outcomes of building StrWhere.

try running it to Immediate window and inspect the strSQLcheck instead of executing.
0
 
LVL 39

Expert Comment

by:stevbe
ID: 9674542
do not use vbCrlf in your SQL strings

  strSQLKey = "SELECT tblPrimaryKeyNames.KeyName"
  strSQLKey = strSQLKey & " FROM tblPrimaryKeyNames" &
  strSQLKey = strSQLKey & " WHERE (((tblPrimaryKeyNames.TableName)=" & """" & strTable & """" & "))"
  strSQLKey = strSQLKey & " GROUP BY tblPrimaryKeyNames.KeyName"
  strSQLKey = strSQLKey & " HAVING (((tblPrimaryKeyNames.KeyName)<>""ID""));"


aside:

Dim intSubID, intCoderID, intRecordCount, intKeyCount As Integer

only intKeyCount get created as an integer all others will be variants, the same with your other declaration lines. In vba you need to declare the data type of each variable individually or else they will default to variant.

Steve
0
 

Author Comment

by:pansophy
ID: 9674642
svenkarlsen>  

This is the SQL statement copied directly from the immediate window (produced using the debug.print command)

SELECT ftblDataEntryTest.ID, ftblDataEntryTest.Battery, ftblDataEntryTest.Relative
FROM ftblDataEntryTest
WHERE (((ftblDataEntryTest.ID)=1) AND ((ftblDataEntryTest.Battery)=1) AND ((ftblDataEntryTest.Relative)="uncle"));

The statement runs when I copy it into a SQL query window.  

Could the module be corrupted??
0
Use Case: Protecting a Hybrid Cloud Infrastructure

Microsoft Azure is rapidly becoming the norm in dynamic IT environments. This document describes the challenges that organizations face when protecting data in a hybrid cloud IT environment and presents a use case to demonstrate how Acronis Backup protects all data.

 
LVL 9

Expert Comment

by:svenkarlsen
ID: 9674795
I aggree with Steve on the Dim. And it could be the source of problem here, - try making an explicit declaration like:

Dim rstCheckKeys As ADODB.Recordset, rsttest As ADODB.Recordset, rstCheckData As ADODB.Recordset, rstAddKeys As ADODB.Recordset

I also agree with Steve in principle on the vbCrLf, - but in this case I shouldn't think it would make any difference since it comes in front of keywords (don't do it in SQL Server pass-through though!).

Regards,
Sven
0
 

Author Comment

by:pansophy
ID: 9676032
I changed my declarations to:

Dim rstCheckKeys As ADODB.Recordset
Dim rsttest As ADODB.Recordset
Dim rstCheckData As ADODB.Recordset
Dim rstAddKeys As ADODB.Recordset

and removed the vbCrLf from all my SQL statements.  Sadly, I receive the same error.  

Another odd piece of information.  In this code I make two different SQL strings.  If I simply change

Set rstAddKeys = CurrentProject.Connection.Execute(strSQLCheck)

to

Set rstAddKeys = CurrentProject.Connection.Execute(strSQLKey)

Using the second SQL statement works just fine.  What about a SQL statement coudl cause the connection to fail??  

As I said, I copied the SQL string directly from the immediate window to a query and it ran perfectly.  So, I'm not even sure what could be wrong with a SQL that would allow it to run directly from a query window but cause a connection error in a module.

Thanks for any insights.
0
 
LVL 9

Expert Comment

by:svenkarlsen
ID: 9676786
Try changing the two SQL Calls to:


rstAddKeys.Execute(strSQLKet), CurrentProject.Connection, adOpenDynamic, adLockOptimistic


rstAddKeys.Execute(strSQLCheck), CurrentProject.Connection, adOpenDynamic, adLockOptimistic
0
 
LVL 9

Expert Comment

by:svenkarlsen
ID: 9676833
Just to be on the safe side: are you up to date with SP's ?

SP3: http://support.microsoft.com/default.aspx?scid=kb;EN-US;326585

And then I forgot, you might try closing rstAddKeys in between SQL calls:

set rstAddKeys =Nothing


Sven
0
 
LVL 9

Expert Comment

by:svenkarlsen
ID: 9676944
Sorry, - i confused your code with another case, - disregard previous msg:
 
rstAddKeys.Execute(strSQLKey), CurrentProject.Connection, adOpenDynamic, adLockOptimistic
rstAddKeys.Execute(strSQLCheck), CurrentProject.Connection, adOpenDynamic, adLockOptimistic

0
 

Author Comment

by:pansophy
ID: 9679026
rstAddKeys.Execute isn't a command, or at least it didn't let me run it as such.  I tried rstAddkeys.open with your suggestion and I got the same connection error.  

I'm really beginning to think the db is just corrupted...
0
 

Author Comment

by:pansophy
ID: 9679216
Okay, lets up this to 200 points.

I exported the three tables I needed for this code to a text file and copied the module to a text file as well to eliminate any corrupted elements from the data/code.

I imported the tables form the text files and copied the code into a module in a new database.  I got the same connection error.  

Better still, I simplified the code to this and still got the error:

Private Sub strProblem()

Dim strSQL As String
Dim rstCheckKeys As ADODB.Recordset

    strSQL = "SELECT ftblDataEntryTest.ID, ftblDataEntryTest.Battery, ftblDataEntryTest.Relative FROM ftblDataEntryTest WHERE (((ftblDataEntryTest.ID)=1) AND ((ftblDataEntryTest.Battery)=4) AND ((ftblDataEntryTest.Relative)=""uncle""));"
   
Set rstCheckData = CurrentProject.Connection.Execute(strSQL)
 
End Sub

If I copy the Select statement into a query it retrieves records just as it should.  I am truly befuddled.

Thanks for keeping the suggestions coming.
0
 

Author Comment

by:pansophy
ID: 9679882
Well I found the solution.

Apparently, using the field name "relative" caused the problem.  Removing the field eliminated the error, so I changed the field name to 'family' and the code runs as it should.  

*sigh*
0
 

Author Comment

by:pansophy
ID: 9679908
svenkarlsen> Is there any way for me to give you the points for effort without misleading those scanning for help by accepting an incorrect solution as correct??  
0
 
LVL 9

Expert Comment

by:svenkarlsen
ID: 9680370
Pan,
that's just one of those things ;-)

You're very kind, but as I did not provide a solution, I suggest you make a posting for point refund and question removal (please see the help for instructions).

Kind Regards,
Sven
0
 
LVL 32

Expert Comment

by:jadedata
ID: 10018713
No comment has been added lately, so it's time to clean up this TA.
I will leave the following recommendation for this question in the Cleanup topic area:

PAQ - no points refunded

Please leave any comments here within the next seven days.
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

jadedata
EE Cleanup Volunteer
0
 

Accepted Solution

by:
SpazMODic earned 0 total points
ID: 10050554
PAQed - no points refunded (of 200)

SpazMODic
EE Moderator
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Overview: This article:       (a) explains one principle method to cross-reference invoice items in Quickbooks®       (b) explores the reasons one might need to cross-reference invoice items       (c) provides a sample process for creating a M…
Preparing an email is something we should all take special care with – especially when the email is for somebody you may not know very well. The pressures of everyday working life stacked with a hectic office environment can make this a real challen…
In Microsoft Access, when working with VBA, learn some techniques for writing readable and easily maintained code.
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question