Problem with VBA script reading from MySql database - mysql

I am having some trouble with a vba script in Excel which should be
reading from a MySql database. The SQL query should only return one
record but actually returns an empty resultset. The generated statement works fine when run through phpMyAdmin.
Here is my code:
Function getClientId(emailAddress As String)
Dim rs As ADODB.Recordset
Dim sql As String
ConnectDB
Set rs = New ADODB.Recordset
sql = "SELECT client_id FROM clients WHERE email_address = '" & emailAddress & "' LIMIT 1"
Debug.Print sql
rs.Open sql, oConn
Debug.Print rs.RecordCount
If (rs.RecordCount = -1) Then
getClientId = Null
Else
getClientId = rs(0)
End If
rs.Close
End Function
EDIT: My database connect function.
Function ConnectDB()
On Error GoTo ErrHandler
Set oConn = New ADODB.Connection
oConn.Open "DRIVER={MySQL ODBC 5.1 Driver};" & _
"SERVER=localhost;" & _
"DATABASE=mydb;" & _
"USER=user;" & _
"PASSWORD=password;" & _
"Option=3"
'Debug.Print oConn
Exit Function
ErrHandler:
MsgBox Err.Description, vbCritical, Err.Source
End Function
The ConnectDB function is connecting ok as I am running other scripts
with it. If anyone can see what I am doing wrong then any help would
be appreciated.
Many thanks in advance.
Garry

MyODBC does not properly provide the RecordCount-Attribute.
Re: Problem with RecordCount with ASP & MySQL
rs.recordcount = -1 with myODBC
Re: ADO Connection RecordCount
So, if you really need the RecordCount, set CursorLocation Property to adUseClient.
If not, just iterate through the RecordSet like this:
Do While Not rs.EOF
'...do your magic
rs.MoveNext
Loop

Use " (double quote) instead of ' (single quote), because you are querying through the ODBC driver.

This could be problem of driver you have selected. My suggestion is (and I may be wrong) - if you are connecting via ODBC it could have different set of commands.

Related

How to resolve a "Could not find installable ISAM error in MySQL connection string in Access module

Access 365/Windows 10
I’m getting the “Could not find installable ISAM” error which I believe means I’ve a problem with my connection string below.
I did a right click, export on a single Access table to the MySQL backend so that I could link it and verify the driver, server, port, database, etc. of that connection against the connection string in the function below. It all looks good. Can you see what I've done wrong?
I have 128 tables to migrate to MySQL and am looking for a efficient, repeatable process; I had high hopes for this code...
'''
Public Function fncExportTables() As Boolean
'Declare Variables...
Dim strCnn As String
Dim rs As Recordset
Dim db As Database
Dim strTp As String
Dim strOriginal As String
'The Connection String required to connect to MySQL.
'I THINK THIS IS THE PROBLEM
strCnn = "DRIVER={MySQL ODBC 8.0 Driver};" & _
"SERVER=myServer;" & _
"PORT=24299;" & _
"DATABASE=myDb;" & _
"USER=myUserName;" & _
"PASSWORD=myPassword;" & _
"OPTION=3;"
strTp = "ODBC Database"
'Trap any Errors...
On Error GoTo Error_fncExportTables
'Open a recordset from the table the conatains
'all the table names we want to Link from the
'MySQL Database.
Set db = CurrentDb
Set rs = db.OpenRecordset("qselMgr", dbOpenSnapshot)
With rs
'Fill the Recordset...
.MoveLast
.MoveFirst
'Enumerate through the Records...
Do Until rs.EOF
'Place the Table Name into the str string variable.
' FieldName (below) would be the Field name in your Access
' Table which holds the name of the MySQL Tables to Link.
strOriginal = !strOriginalName
'Make sure we are not dealing will an empty string..
If Len(strOriginal) > 0 Then
'Link the MySQL Table to this Database.
'ERROR TRIGGERS ON THE LINE BELOW
DoCmd.TransferDatabase acExport, strTp, strCnn, _
acTable, strOriginal, strOriginal
End If
'move to the next record...
.MoveNext
Loop
End With
'We're done...
Exit_fncExportTables:
'Clear Variables and close the db connection.
Set rs = Nothing
If Not db Is Nothing Then db.Close
Set db = Nothing
Exit Function
Error_fncExportTables:
'If there was an error then display the Error Msg.
MsgBox "Export Table Error:" & vbCr & vbCr & _
Err.Number & " - " & Err.Description, _
vbExclamation, "Export Table Error"
Err.Clear
Resume Exit_fncExportTables
End Function
'''

Connection to Access 2013 database with VB6

I am trying to connect to an Access database 2013 (.accdb) from VB6, and keep getting errors. My code is as follows:
Dim db_file As String
Dim statement As String
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
' Get the data.
db_file = App.Path
If Right$(db_file, 1) <> "\" Then db_file = db_file & "\"
db_file = db_file & "FluidFlo.accdb"
' Open a connection.
Set conn = New ADODB.Connection
conn.ConnectionString = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & db_file & ";" & "Persist Security Info=False"
conn.Open '(PROBLEM IS HERE)
' Select the data.
statement = "SELECT strEmpName FROM tblEmployees ORDER BY strEmpName"
' Get the records.
Set rs = conn.Execute(statement, , adCmdText)
' Load the results into the ComboBox
Do Until rs.EOF
cboUsername.AddItem rs!strEmpName
rs.MoveNext
Loop
' Close the recordset and connection.
rs.Close
conn.Close
I am trying to load a table in to a combobox in the program, and assuming my connection string is having an error. I changed the Provider=Microsoft.ACE.OLEDB.12.0; to Provider=Microsoft.ACE.OLEDB.15.0; and still no luck. Keep getting an error.
Does anyone have an idea of how to connect to an .accdb database, whether SQL commands or any? Thanks in advance...(pulling my hair out...)

Interesting issue with ADODB connection: UDF using ADODB works fine when called from VBA code, but it returns error when called from EXCEL cell

I have been using ADODB connection from within Excel in order to connect to MySql databases and retrieve values.
The essence of my code is as follows:
Public Function ODPH(B0 As Range, sqlstr As Variant)
Dim oconn As ADODB.Connection
Dim rs As ADODB.Recordset
On Error GoTo error_handler
'Connect to MySql. Assign default values if connection string is missing!
ipDriver = "{MySQL ODBC 5.2 Unicode Driver}"
ipType = "MySql"
If IsEmpty(ipHost) Then ipHost = "HHHH"
If IsEmpty(ipUser) Then ipUser = "UUUU"
If IsEmpty(ipdbName) Then ipdbName = "DDDD"
If IsEmpty(ipPasswd) Then ipPasswd = "PPPP"
strConn = "DRIVER=" & ipDriver & ";" & _
"SERVER=" & ipHost & ";" & _
"DATABASE=" & ipdbName & ";" & _
"USER=" & ipUser & ";" & _
"PASSWORD=" & ipPasswd & ";" & _
"Option=" & ipOption
Set oconn = New ADODB.Connection
oconn.Open strConn
oconn.CursorLocation = adUseClient
'oconn.CursorLocation = adUseServer
Set rs = New ADODB.Recordset
' rs.Open sqlstr, oconn, adLockOptimistic
' rs.Open sqlstr, oconn, adLockReadOnly
rs.Open sqlstr, oconn, adOpenStatic, adLockOptimistic
rs.Open sqlstr, oconn
If rs.EOF Then
'MsgBox "No records returned!"
ODPH = "#No record at db"
Exit Function
Else
'rs.MoveLast
rCount = rs.RecordCount
Select Case rCount
Case Is > 1
ODPH = "#many records from db"
Exit Function
Case Else
Select Case rs.Fields.Count
Case Is > 1
ODPH = "#many columns from db"
Exit Function
Case Else
Select Case IsNull(rs.Fields(0).Value)
Case Is = True
ODPH = "#null at db"
Exit Function
Case Else
aux = rs(0).Value
Select Case IsNumeric(aux)
Case Is = True
ODPH = CDbl(aux)
Exit Function
Case Else
ODPH = aux
Exit Function
End Select
End Select
End Select
End Select
End If
'Error handler
error_handler:
ODPH = Err.Description
Exit Function
End Function
My issue is that:
This code works well when it is called from another VBA sub or function.
But this function returns the following error when it is called from one excel cell as a UDF function:
"Arguments are of the wrong type, are out of acceptable range, or are in conflict with one another." (Error number 3001)
I really could not understand why one set of code returns no error when it is called by VBA editor whereas it returns this error when it is called from one excel cell as a user-defined function!
Any help is appreciated.
Best regards,
By definition, UDF needs to return something and you are missing the return type like:
Public Function ODPH(B0 As Range, sqlstr As Variant) As Variant
Calling it from another macro works, because VBA (or almost all programming languages) don't really care if you have a receiving variable of function.

Access ADO: operation is not allowed when the object is closed error message

I am using Access 2003 with a local table which will later be transferred and linked to a SQL Server 2008 table. I am using the following code but get the error: "Run-time error 3704: Operation is not allowed when the object is closed" on the cnn.Execute line.
sub test()
On Err GoTo Err_Sub
Dim cnn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim str As String
Dim strSQL As String
'Open a connection.
Set cnn = New ADODB.Connection
cnn.ConnectionString = _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & CurrentDb.Name & ";" & _
"Persist Security Info=False"
strSQL = Me.RecordSource
str = Mid(strSQL, InStr(strSQL, "Where "))
strSQL = "Update myTable SET Active = False " & str
Set rs = cnn.Execute(strSQL)
If Not rs Is Nothing Then rs.Close
Exit_Sub:
Set rs = Nothing
Exit Sub
Err_Sub:
MsgBox Err.Description
Resume Exit_Sub
End Sub
Ran into this error as well (in my case I am using a Stored Procedure to retrieve some information). I had made some changes which caused the execution to malfunction.
The error disappeared when I put SET NOCOUNT ON as the first statement of the Stored Procedure.
Try CurrentProject.Connection.Execute strSQL instead of declaring your cnn object.
Well that's simple. You need to add
cnn.Open
somewhere before cnn.Execute
also, don't forget to call
cnn.Close
Set cnn = nothing
before exiting from the sub
I recently ran into this issue as well. My error came up because I was naming one of the columns in the sql query 'Pit#'. I am fairly certain that it was the # that caused this error to happen for me. I hope this helps someone in the future.
Thanks -- Shell

How to save an ADO recordset into a new local table in Access 2003?

I'm trying to import tables from a FoxPro 9.0 database into Access 2003. So far, from Google searches and many trials, the only way for me to connect to the tables is through an OLE DB connection programatically. I have set up 3 ODBC connections with different configurations but none of them work: I get "unspecified errors" that I can't find any information on.
With OLE DB I can succesfully connect to the FoxPro database, and import tables in ADO recordsets. The problem is that I can't save the recordset into new table in the local database using SQL. The ADO recordsets behave differently than tables, so I can't query them. The code below gives me a "type mismatch" error at DoCmd.RunCommand ("select * from " & rst & " INTO newClients").
Sub newAdoConn()
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim strSQL As String
Dim decision As Integer
Set cnn = New ADODB.Connection
cnn.ConnectionString = "Provider=vfpoledb;" & _
"Data Source=s:\jobinfo\data\jobinfo.dbc;" & _
"Mode=ReadWrite|Share Deny None;" & _
"Collating Sequence=MACHINE;" & _
"Password=''"
strSQL = "Select * from Jobs"
cnn.Open
Set rst = cnn.Execute("Select * from clients")
If rst.EOF = False Then
Do While Not rst.EOF
decision = MsgBox(rst.Fields!ID & " " & rst.Fields!fname & " " & rst.Fields!lname & vbCrLf & vbCrLf & "Continue?", vbYesNo)
If decision = vbYes Then
rst.MoveNext
Else
Exit Do
End If
Loop
End If
DoCmd.RunCommand ("select * from " & rst & " INTO newClients")
rst.Close
Set rst = Nothing
cnn.Close
Set cnn = Nothing
End Sub
I finally worked out a decent solution. It involves saving the ado recordset from memory to an excel file using the copyFromRecordset function, and then linking the file programmatically to a table in excel using the TransferSpreadsheet()...
Sub saveToExcel()
Dim cnn As ADODB.Connection
'declare variables
Dim rs As ADODB.Recordset
Dim strSQL As String
Dim decision As Integer
Dim colIndex As Integer
' Dim fso As New FileSystemObject
' Dim aFile As File
'set up connection to foxpro database
Set cnn = New ADODB.Connection
cnn.ConnectionString = "Provider=vfpoledb;" & _
"Data Source=s:\jobinfo\data\jobinfo.dbc;" & _
"Mode=ReadWrite|Share Deny None;" & _
"Collating Sequence=MACHINE;" & _
"Password=''"
cnn.Open
Set rs = cnn.Execute("Select * from clients")
'Create a new workbook in Excel
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
Set oExcel = CreateObject("Excel.Application")
Set oBook = oExcel.Workbooks.Add
Set oSheet = oBook.Worksheets(1)
oSheet.Name = "clients"
' Copy the column headers to the destination worksheet
For colIndex = 0 To rs.Fields.Count - 1
oSheet.Cells(1, colIndex + 1).Value = rs.Fields(colIndex).Name
Next
'Transfer the data to Excel
oSheet.Range("A2").CopyFromRecordset rs
' Format the sheet bold and auto width of columns
oSheet.Rows(1).Font.Bold = True
oSheet.UsedRange.Columns.AutoFit
'delete file if it exists - enable scripting runtime model for this to run
'If (fso.FileExists("C:\Documents and Settings\user\Desktop\clients.xls")) Then
' aFile = fso.GetFile("C:\Documents and Settings\user\Desktop\clients.xls")
' aFile.Delete
'End If
'Save the Workbook and Quit Excel
oBook.SaveAs "C:\Documents and Settings\user\Desktop\clients.xls"
oExcel.Quit
'Close the connection
rs.Close
cnn.Close
MsgBox ("Exporting Clients Done")
'link table to excel file
DoCmd.TransferSpreadsheet acLink, acSpreadsheetTypeExcel5, "clientsTest", "C:\Documents and Settings\user\Desktop\clients.xls", True
End Sub
What you will have to do is open the FoxPro table as a recordset and open the local table as another recordset. You can then loop through the FoxPro recordset and do something like this
Do until FoxProRst.EOF
LocatRst.AddNew
LocalRst!SomeField1=FoxProRst!SomeField1
LocalRst!SomeField2=FoxProRst!SomeField2
LocalRst!SomeField3=FoxProRst!SomeField3
LocalRst.Update
FoxProRst.MoveNext
Loop
It might not be the quickest way but it will work
Let me just sketch another approach with SQL queries, that could simplify:
'...
'not required for first time test:
'cnn.Execute("DROP TABLE MyNewTable")
'...
'create the new table in the destination Access database
cnn.Execute("CREATE TABLE MyNewTable (MyField1 int, MyField2 VARCHAR(20), MyField3 Int)")
'insert data in the new table from a select query to the original table
Dim sSQL as string, MyOriginalDBPath as String
sSQL = "INSERT INTO MyNewTable (MyField1, MyField2, MyField3) SELECT OriginalField1, OriginalField2, OriginalField3 FROM [" & MyOriginalDBPath & ";PWD=123].clients"
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
rs.Open sSQL, cnn, adOpenForwardOnly, adLockReadOnly, adCmdText
'...
Note: this 'draft' idea assumes that the connection string is made to the Access database and the connection to the original database would be inside the SQL string, but i have not idea about the correct sintaxis. I have only tested this approach with different access databases.
Note that this is for Access: ...[" & MyOriginalDBPath & ";PWD=123]...
The Jet database engine can reference external databases in SQL statements by using a special syntax that has three different formats:
[Full path to Microsoft Access database].[Table Name]
[ISAM Name;ISAM Connection String].[Table Name]
[ODBC;ODBC Connection String].[Table Name]
...
You can use an ODBC Data Source Name (DSN) or a DSN-less connection string:
DSN: [odbc;DSN=;UID=;PWD=]
DSN-less: [odbc;Driver={SQL Server};Server=;Database=;
UID=;PWD=]
Some references:
Querying data by joining two tables in two database on different servers
C# - Join tables from two different databases using different ODBC drivers
Why not use ODBC to link to the table? http://support.microsoft.com/kb/225861