I have installed the mySQL server on my computer and created the Database called Sales consisting of one table called Orders. You can also find the table in the SQL fiddle here:
CREATE TABLE Orders (
OrderID INT,
Customer VARCHAR(255),
Revenue VARCHAR(255)
);
INSERT INTO Orders
(OrderID, Customer, Revenue)
VALUES
("1", "Customer A","400"),
("2", "Customer A","200"),
("3", "Customer B","600"),
("4", "Customer C","150"),
("5", "Customer C","800"),
("6", "Customer C","300");
Then I created an Excel file and activated Microsoft ActiveX Data Objects 2.8 Library.
Now I wanted to connect to the Database above and extract data from it using the following VBA script:
Sub ConnectDB()
Set conn = New ADODB.Connection
conn.ConnectionString = "DRIVER={MySQL ODBC 3.51 Driver}; SERVER=localhost; DATABASE=Sales; UID=root; PWD=mypassword; OPTION=3"
Set rs = New ADODB.Recordset
Set rs = conn.Execute("SELECT * FROM sales.orders;")
Sheet1.Range("A1").Value = rs
End Sub
However, when I run this VBA I get runtime error 3704. As far as I can tell this error is probably caused by these lines:
Set rs = New ADODB.Recordset
Set rs = conn.Execute("SELECT * FROM sales.orders;")
because if I delete them the VBA runs without the error.
What do I need to change in my code to extract the Data from the mySQL database?
your connection is not open
try this
Sub ConnectDB()
Set conn = New ADODB.Connection
conn.ConnectionString = "DRIVER={MySQL ODBC 3.51 Driver}; SERVER=localhost; DATABASE=Sales; UID=root; PWD=mypassword; OPTION=3"
conn.open
Set rs = New ADODB.Recordset
Set rs = conn.Execute("SELECT * FROM sales.orders;")
Sheet1.Range("A1").Value = rs
End Sub
Don't use Execute - that is for running a command on the database, not for returning a recordset.
Sub ConnectDB()
Set conn = New ADODB.Connection
conn.ConnectionString = "DRIVER={MySQL ODBC 3.51 Driver}; SERVER=localhost; DATABASE=Sales; UID=root; PWD=mypassword; OPTION=3"
conn.Open
Set rs = New ADODB.Recordset
rs.Open "SELECT * FROM sales.orders;", conn
Sheet1.Range("A1").Value = rs
End Sub
And if your string fields return what looks like garbage, you are going to have to do a little more than that too.
Try it like
Dim oConn As ADODB.Connection
Then
Private Sub ConnectDB()
Set oConn = New ADODB.Connection
Dim str As String
str = "DRIVER={MySQL ODBC 5.1 Driver};" & _
"SERVER=XXX.XXX.XXX.XXX replace with your IP address" & ";" & _
"PORT=replace with the port you are using, usually 3306" & ";" & _
"DATABASE=replace with the name of your databese" & ";" & _
"USER=replace with the username you are using to connetc yourself to the databes" & ";" & _
"PASSWORD=replace with password you are using to connect to the databse" & ";" & _
"Option=3"
oConn.Open str
End Sub
And Finally
Sub InsertData()
Dim Rs As ADODB.Recordset
Dim Requete As String
Set Rs = New ADODB.Recordset
Call ConnectDB
Requete = "SELECT * FROM sales.orders;"
Rs.Open Requete, oConnect, adOpenDynamic, adLockOptimistic
End With
oConnect.Close
Set Rs = Nothing
End Sub
Assuming you are using Excel 2000 or newer there is a surprisingly easy way to do this, and to even get the MySQL column names.
Public Sub insert_data()
Dim dbConn As New ADODB.Connection, rs As New ADODB.Recordset, sql As String
Dim ws As New Excel.Worksheet, cCtr As Long, numFields As Long
Set ws = ThisWorkbook.Sheets("Sheet1")
dbConn.ConnectionString = "[put your connection string here]"
dbConn.Open
sql = "SELECT * FROM sales.orders;"
Set rs = New ADODB.Recordset
Set rs = dbConn.Execute(sql, , adCmdText)
With ws
' Get the number of columns:
numFields = rs.Fields.Count
' Put the column names into the first row of your worksheet:
For cCtr = 1 To numFields
.Cells(1, cCtr).Value = rs.Fields(cCtr - 1).name
Next cCtr
' Put all the recordset data into your worksheet,
' starting from the worksheet's second row:
.Cells(2, 1).CopyFromRecordset rs
End With
dbConn.Close
End Sub
I have the following sub:
Dim oConn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Set rst = New ADODB.Recordset
Set oConn = New ADODB.Connection
oConn.Open "DRIVER={MySQL ODBC 5.1 Driver};" & _
"SERVER=server;" & _
"DATABASE=db;" & _
"USER=user;" & _
"PASSWORD=pass;" & _
"Option=3"
Set cmd = New ADODB.Command
cmd.ActiveConnection = oConn
table_name = Sheets("Master").Range("S2").Value
SQLstr = "Select * From " & table_name
rst.Open SQLstr, oConn, adOpenDynamic, adLockOptimistic
lRow = Cells(Rows.Count, 1).End(xlUp).Row
lCol = Cells(1, Columns.Count).End(xlToLeft).Column
For rowindx = 2 To lRow
rst.AddNew
For fieldIndx = 1 To lCol
rst.Fields(Cells(1, fieldIndx).Value) = Cells(rowindx, fieldIndx).Value
Next fieldIndx
Next rowindx
rst.UpdateBatch
rst.Close
oConn.Close
Set rst = Nothing
Set oConn = Nothing
MsgBox ("Query Successful")
This gives me the "The MySQL server is running with the --read-only option so it cannot execute the statement" at the rst.AddNew step.
However, when I run a separate function attached to a different macro (same database, same server), everything gets executed as expected. The database is not read-only.
Dim oConn As New ADODB.Connection
Dim cmd As New ADODB.Command
Set oConn = New ADODB.Connection
oConn.Open "DRIVER={MySQL ODBC 5.1 Driver};" & _
"SERVER=server;" & _
"DATABASE=database;" & _
"USER=user;" & _
"PASSWORD=password;" & _
"Option=3"
Set cmd = New ADODB.Command
cmd.ActiveConnection = oConn
cmd.CommandText = strSQL
cmd.Execute
oConn.Close
MsgBox ("Query Successful")
What's wrong with the first block? Does recordset default to read-only?
Just had to change 'adLockOptimistic' to 'adLockBatchOptimistic'
I'm doing something like this for the first time and it seems incredibly hard to find any useful information at all.
What I want to do:
Pass a select-query to a MySQL database and show the result in a table.
I've got that far by now: I have a button on a form and when clicked the following happens
Option Compare Database
Sub RunPassThrough(strSQL As String)
Dim ConnectionString As String
Dim Server As String
Dim User As String
Dim Pwd As String
Dim DatabaseName As String
Dim Cn As ADODB.Connection
Dim Rs As ADODB.Recordset
' Server Hostname (or IP)
Server = "192.168.178.10"
User = "user"
Pwd = "mypass"
DatabaseName = "myDB"
ConnectionString = "Provider=MSDASQL;Driver={MYSQL ODBC 5.1 DRIVER};" & _
"Server=" & Server & ";Database=" & DatabaseName
Set Cn = New ADODB.Connection
Cn.CursorLocation = adUseClient
Cn.Mode = adModeShareDenyNone
Cn.Open ConnectionString, User, Pwd
Set Rs = New ADODB.Recordset
Rs.Open strSQL, Cn, adOpenDynamic, adLockReadOnly
'Set Rs = Cn.Execute("select * from SurveyResults limit 10;")
End Sub
Private Sub Befehl0_Click()
Dim SQL As String
SQL = "select * from SurveyResults limit 10;"
RunPassThrough (SQL)
End Sub
I know that Rs.Open strSQL, Cn, adOpenDynamic, adLockReadOnly returns an ADO recordset and I could do things with it using VBA, but all I want is to show that recorod set to the user in table.
something like OpenRecordset("Rs", as a table that the user can see)
can someone please point me into the right direction I'm going crazy...
I figured it out. My problem was simply that the ReturnsRecords Property is set to false by default.
it works now, so I'm posting a answer if anyone ever needs it.
Sub RunPassThrough(strSQL As String)
Dim Server As String
Dim User As String
Dim Pwd As String
Dim DatabaseName As String
Dim qdfPassThrough As DAO.QueryDef, MyDB As Database
Dim strConnect As String
' Server Hostname (or IP)
Server = "192.168.178.10"
User = "user"
Pwd = "mypass"
DatabaseName = "database"
For Each qdf In CurrentDb.QueryDefs
If qdf.Name = "PassQuery" Then
CurrentDb.QueryDefs.Delete "PassQuery"
Exit For
End If
Next
strConnect = "ODBC;DRIVER={MYSQL ODBC 5.1 DRIVER};SERVER=" & Server & ";DATABASE=" & DatabaseName & ";Uid=" & User & ";Pwd=" & Pwd & ";"
Set MyDB = CurrentDb()
Set qdfPassThrough = MyDB.CreateQueryDef("PassQuery")
qdfPassThrough.Connect = strConnect
qdfPassThrough.SQL = strSQL
qdfPassThrough.Close
Application.RefreshDatabaseWindow
MyDB.QueryDefs("PassQuery").ReturnsRecords = True
DoCmd.OpenQuery "PassQuery", acViewNormal, acReadOnly
DoCmd.Maximize
End Sub
I am getting an error and I don't understand what is the problem. Here is my code
Sub test()
Dim rs As ADODB.Recordset
Dim sqlstr As String ' SQL to perform various actions
Dim oConn As ADODB.Connection
Set oConn = New ADODB.Connection
oConn.Open "DRIVER={MySQL ODBC 5.3 Unicode Driver};" & _
"SERVER=ETS-DEV-01;" & _
"DATABASE=reporting;" & _
"USER=guest_user;" & _
"PASSWORD=0X4ZT9kwsY%yGOp;" & _
"Option=3"
sqlstr = "select * from tveuptimes"
rs.Open sqlstr, oConn
End Sub
I am getting the error:
Run-time error '91'
Object variable or with block variable not set.
I don't understand what i am doing wrong.
The line Set oConn = New ADODB.Connection isn't necessary. Instead, when you dimension rs and oConn add the word New before the type, like this:
Sub test()
Dim rs As New ADODB.Recordset
Dim sqlstr As String
Dim oConn As New ADODB.Connection
oConn.Open "DRIVER={MySQL ODBC 5.3 Unicode Driver};" & _
"SERVER=ETS-DEV-01;" & _
"DATABASE=reporting;" & _
"USER=guest_user;" & _
"PASSWORD=0X4ZT9kwsY%yGOp;" & _
"Option=3"
sqlstr = "select * from tveuptimes"
rs.Open sqlstr, oConn
End Sub
Here's a good tutorial: http://analysistabs.com/excel-vba/ado-sql-macros-connecting-database/
I would appreciate some help solving problems accessing a MySQL database from Excel.
I've created the database in phpmyadmin. I've also been able to manually import data via a CSV file into the SQL database on phhpmyadmin.
So, I'm sure that I've got the right IP address, user ID and password for the database.
I've also read various posts about how to configure ODBC connections from Windows to SQL and I think I've followed the right instructions.
However, I can't seem to get the code to work from VBA. I keep getting various errors.
Here's the code I've been using, minus the actual database names and User IDs.
Private Sub cmdInsertData_Click()
Dim oConn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim Pwd As String
Dim SQLStr As String
Dim Svr_Nm As String
Dim UID As String
Dim Dbs_Nm As String
' Input Parameters
Pwd = "mypassword"
UID = "myuser"
srvr_nm = "xxx.xxx.xx.xx:yyyy"
Dbs_Nm = "myname"
Set rs = New ADODB.Recordset
Set oConn = New ADODB.Connection
SQLStr = "DRIVER={MySQL ODBC 5.3 ANSI Driver};"
SQLStr = SQLStr & "SERVER=" & srvr_nm & ";DATABASE=" & Dbs_Nm & ";USER=" & UID & ";PASSWORD=" & Pwd & ";Option=3"
oConn.Open SQLStr
MsgBox "Connected to " & Dbs_Nm & " via " & srvr_nm
End Sub
I've reset the code as follows. The error message is generated by the line "oConn.Open SQLStr". The error generated is
Run-time error ‘-2147467259 (80004005)’:
[MySQL][ODBC 5.3(a) Driver]Unknown MySQL server host ‘209.159.152.202:2083’ (0)
New Code:
Private Sub CheckConnection()
Dim oConn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim Pwd As String
Dim SQLStr As String
Dim Svr_Nm As String
Dim Usr_ID As String
Dim Dbs_Nm As String
' Input Parameters
Pwd = "mypassword"
Usr_ID = "myID"
srvr_nm = "209.159.152.202:2083"
Dbs_Nm = "mydatabase"
Set rs = New ADODB.Recordset
Set oConn = New ADODB.Connection
SQLStr = "DRIVER={MySQL ODBC 5.3 ANSI Driver};"
SQLStr = SQLStr & "SERVER=" & srvr_nm & ";DATABASE=" & Dbs_Nm & ";USER=" & Usr_ID & ";PASSWORD=" & Pwd & ";Option=3"
oConn.Open SQLStr
MsgBox "Connected to " & Dbs_Nm & " via " & srvr_nm
End Sub
Thanks for the suggestion about adding the Port= as a separate variable. I've tried that however (see new code) and it still doesn't work.
Private Sub CheckConnection()
Dim oConn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim Pwd As String
Dim SQLStr As String
Dim Svr_Nm As String
Dim Usr_ID As String
Dim Dbs_Nm As String
Dim Port_Nm As String
' Input Parameters
Pwd = "mypassword"
Usr_ID = "myID"
Svr_Nm = "209.159.152.202"
Dbs_Nm = "mydatabase"
Port_Nm = "2083"
Set rs = New ADODB.Recordset
Set oConn = New ADODB.Connection
SQLStr = "DRIVER={MySQL ODBC 5.3 ANSI Driver};"
SQLStr = SQLStr & "Server=" & Svr_Nm & ";Port=" & Port_Nm & ";Database=" & Dbs_Nm & ";User=" & Usr_ID & ";Password=" & Pwd & ";Option=3"
oConn.Open SQLStr
MsgBox "Connected to: " & Dbs_Nm & " via " & Svr_Nm
End Sub
I still get the same error message at the same place.