Solved

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

Posted on 2003-11-03
15
1,242 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
15 Comments
 
LVL 9

Expert Comment

by:svenkarlsen
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 9

Expert Comment

by:svenkarlsen
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 9

Expert Comment

by:svenkarlsen
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
PAQed - no points refunded (of 200)

SpazMODic
EE Moderator
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

The first two articles in this short series — Using a Criteria Form to Filter Records (http://www.experts-exchange.com/A_6069.html) and Building a Custom Filter (http://www.experts-exchange.com/A_6070.html) — discuss in some detail how a form can be…
QuickBooks® has a great invoice interface that we were happy with for a while but that changed in 2001 through no fault of Intuit®. Our industry's unit names are dictated by RUS: the Rural Utilities Services division of USDA. Contracts contain un…
Familiarize people with the process of utilizing SQL Server views from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Access…
With Microsoft Access, learn how to specify relationships between tables and set various options on the relationship. Add the tables: Create the relationship: Decide if you’re going to set referential integrity: Decide if you want cascade upda…

728 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now