Extract values from mySQL database into Excel using VBA - mysql

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

Related

Execute SQL written in a textbox with VBA

With reference to this question: Avoid new line seperators in mySQL query within VBA code, I wanted to execude a SQL statement that is written in a textbox in the Excel-File.
Therefore, I created a textbox called SqlQuery1 looking like this:
In the VBA I refered to the textbox within the SqlString:
Sub Get_Data_from_DWH ()
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Set conn = New ADODB.Connection
conn.ConnectionString = "DRIVER={MySQL ODBC 5.1 Driver}; SERVER=XX.XXX.XXX.XX; DATABASE=bi; UID=testuser; PWD=test; OPTION=3"
conn.Open
SqlString = ThisWorkbook.Sheet1.Shapes("SqlQuery1").OLEFormat.Object.Text
Set rs = New ADODB.Recordset
rs.Open strSQL, conn, adOpenStatic
Sheet1.Range("A1").CopyFromRecordset rs
rs.Close
conn.Close
End Sub
However, I get runtime error 438 on the SqlString.
Do you have any idea what I need to change to make it work?
Thisworkbook.Sheet1 is not a valid object path, try instead:
SqlString = ThisWorkbook.Sheets("Sheet1").Shapes("SqlQuery1").OLEFormat.Object.Text
Or just
SqlString = Sheet1.Shapes("SqlQuery1").OLEFormat.Object.Text
And make sure the sheet is definitely named "Sheet1"
Also, you need to change
rs.Open strSQL, conn, adOpenStatic
to this:
rs.Open SqlString, conn, adOpenStatic
And you should probably use
Dim SqlString as String
at the start of the routine
You're definitely on the right track here and I can see that you've tried solving this error! :-)
Your issue is with the rs.Open part, as far as I can see. I've shuffled your code around a bit. As far as I can see, you did not add the ADODB.Command part. I've added this in the code snippet below.
A word of advice to save time in larger modules; declare your connection as a private global string at the beginning, so you can access it later on in the module.
Private Const CONNECTION As String = "DRIVER={MySQL ODBC 5.1 Driver}; SERVER=XX.XXX.XXX.XX; DATABASE=bi; UID=testuser; PWD=test; OPTION=3"
Sub Get_Data_from_DWH()
Dim cmd As ADODB.Command
Dim conn As ADODB.CONNECTION
Dim rs As ADODB.Recordset
Set conn = New ADODB.CONNECTION
conn.Open CONNECTION
conn.CommandTimeout = 900
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1")
If Not conn.State = ADODB.adStateOpen Then GoTo Bugcatcher
Set cmd = New ADODB.Command
cmd.ActiveConnection = CONNECTION
cmd.CommandText = ws.Shapes("TextBox 2").OLEFormat.Object.Text
cmd.CommandType = adCmdText
Set rs = cmd.Execute
ws.Range("A1").CopyFromRecordset rs
Bugcatcher:
Exit Sub
End Sub

copy data form sqlserver database to access database and vice versa

I have built a program by ms access as a front and save DATA IN sql server database. Also I have some local table in my program.
My program is connected to sql server by connection string and i can read, write, delete and update data.Sometimes I need to copy result of a query to my local table into access and sometimes I want to append one of my access table to sql table
I have written a connection and tried to executed it like this:
Function CopyData()
Dim cn as ADODB.Connection
Dim strServer, strDatabase, strUsername, strPassword As String
Dim strConnectionString As String
strServer = "10.25.2.120"
strDatabase = "dbKala"
strUsername = "javid"
strPassword = "1234"
strConnectionString = "Provider=SQLOLEDB;Data Source=" & strServer & ";Initial Catalog=" & strDatabase & ";User ID=" & strUsername & ";Password=" & strPassword & ";"
Set cn = New ADODB.Connection
cn.ConnectionString = strConnectionString
cn.CommandTimeout = 0
cn.Open
cn.Execute "INSERT INTO GetTelServer Select * FROM dbo.telefone"
End Function
but data isn't copied from sql to access and show me a message about invalid object my access table
I need to help me how to copy a query from sql to access table and vice verse
This task would be a lot easier with linked DAO.Tables, but that needs proper ODBC-Driver for SQL-Server.
If Ms-Access and SQL-Servers bitness match (x64) you can try using OPENROWSET on SQL-Server to access Ms-Access tables from there.
E.g
INSERT INTO SqlServerTable (SqlServerField) SELECT AccessField FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'C:\Program Files\Microsoft Office\OFFICE11\SAMPLES\Northwind.mdb';
'admin';'',AccessTable);
If bitness doesn't match, you have to create 2 different connections and use recordsets (or Action-Query for insert)
One rs is to select the data, second is for inserts:
Dim cn As ADODB.Connection, rs As ADODB.Recordset
Dim cn2 As ADODB.Connection, rs2 As ADODB.Recordset
Set cn = New ADODB.Connection
cn.Open "Provider=SQLNCLI11;Server=server;Database=db;Trusted_Connection=yes;"
Set cn2 = New ADODB.Connection
cn2.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Path\To\AccessDb;"
Set rs = cn.Execute("SELECT SqlServerField FROM SQLSERVERTable")
Set rs2 = cn2.Execute("SELECT AccessField FROM AccessTable")
Do Until rs2.Eof
rs.AddNew
rs.Fields("SqlServerField").Value = rs2.Fields("AccessField").Value
rs.Update
rs2.MoveNext
Loop
rs.Close
rs2.Close
cn.Close
cn2.Close
Of course the fields data-types have to be compatible.

Trying to connect a mysql database to an excel sheet using visual basics

I feel like this is a simple problem but i cant seem to figure it out. I am trying to establish a connection between my excel sheet and my mysql server but keep getting the error "Run-time error '-2147467259 (80004005)':
[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified" I have the necessary drivers installed so i am unsure where to go from here, this is the code i have so far
Dim conn As New ADODB.Connection
Dim TableName As String
Dim sqlstr As String
Dim rs As ADODB.Recordset
Dim CRow As Long, Trow As Long
Dim Column1 As Integer, Column2 As Integer
Set conn = New ADODB.Connection
conn.Open ("DRIVER = {MySQL ODBC 5.3 Unicode Driver}" _
& ";SERVER=127.0.0.1" _
& ";DATABASE=tmi_stock" _
& ";UID=root" _
& ";PWD=MyRoot2018")
Set rs = New ADODB.Recordset
sqlstr = "INSERT INTO tester VALUE(1, 2)"
rs.Open sqlstr, conn, adOpenStatic
Set rs = Nothing
conn.Close
Set conn = Nothing

Connect to an SQL database from EXCEL

I have gone through a few tutorials already and my connection keeps failing, I have tried a lot of different ways of connecting.
I have a connection to mySQL through the mySQL workbench. I am using the IP address and the Port number and then my credentials to login. This works well and I am able to do the queries I need.
I am now trying to access this database through Excel, preferably through VBA. I tried to create a new connection but nothing I do seems to work. I am not sure what to put into my strConn string.
I am currently using:
Options Explicit
Private Sub CommandButton2_Click()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim strConn As String
Set cn = New ADODB.Connection
strConn = "DRIVER={MySQL ODBC 5.3.7 Driver};" & _
"SERVER=XXX.XXX.X.X;" & _
"PORT=3306" & _
"DATABASE=cahier_de_lab;" & _
"UID=xxx;" & _
"PWD=xxx;" & _
"Option=3"
cn.Open strConn
' Find out if the attempt to connect worked.
If cn.State = adStateOpen Then
MsgBox "Welcome to Pubs!"
Else
MsgBox "Sorry. No Pubs today."
End If
' Close the connection.
cn.Close
End Sub
Thanks for your help!
Export from Excel to SQL Server.
Sub InsertInto()
'Declare some variables
Dim cnn As adodb.Connection
Dim cmd As adodb.Command
Dim strSQL As String
'Create a new Connection object
Set cnn = New adodb.Connection
'Set the connection string
cnn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Northwind;Data Source=Excel-PC\SQLEXPRESS"
'cnn.ConnectionString = "DRIVER=SQL Server;SERVER=Excel-PC\SQLEXPRESS;DATABASE=Northwind;Trusted_Connection=Yes"
'Create a new Command object
Set cmd = New adodb.Command
'Open the Connection to the database
cnn.Open
'Associate the command with the connection
cmd.ActiveConnection = cnn
'Tell the Command we are giving it a bit of SQL to run, not a stored procedure
cmd.CommandType = adCmdText
'Create the SQL
strSQL = "UPDATE TBL SET JOIN_DT = '2013-01-22' WHERE EMPID = 2"
'Pass the SQL to the Command object
cmd.CommandText = strSQL
'Execute the bit of SQL to update the database
cmd.Execute
'Close the connection again
cnn.Close
'Remove the objects
Set cmd = Nothing
Set cnn = Nothing
End Sub
OR . . . .
Import from SQL Server into Excel . . . . .
Sub Create_Connectionstring()
Dim objDL As MSDASC.DataLinks
Dim cnt As ADODB.Connection
Dim stConnect As String 'Instantiate the objects.
Set objDL = New MSDASC.DataLinks
Set cnt = New ADODB.Connection
On Error GoTo Error_Handling 'Show the Data-link wizard
stConnect = objDL.PromptNew 'Test the connection.
cnt.Open stConnect 'Print the string to the VBE Immediate Window.
Debug.Print stConnect 'Release the objects from memory.
exitHere:
cnt.Close
Set cnt = Nothing
Set objDL = Nothing
Exit Sub
Error_Handling: 'If the user cancel the operation.
If Err.Number = 91 Then
Resume exitHere
End If
End Sub

How can VBA connect to MySQL database in Excel?

Dim oConn As ADODB.Connection
Private Sub ConnectDB()
Set oConn = New ADODB.Connection
Dim str As String
str = "DRIVER={MySQL ODBC 5.2.2 Driver};" & _
"SERVER=sql100.xtreemhost.com;" & _
"PORT=3306" & _
"DATABASE=xth_9595110_MyNotes;" & _
"UID=xth_9595110;" & _
"PWD=myPassword;" & _
"Option=3"
''' error '''
oConn.Open str
End Sub
Private Sub InsertData()
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
ConnectDB
sql = "SELECT * FROM ComputingNotesTable"
rs.Open sql, oConn, adOpenDynamic, adLockOptimistic
Do Until rs.EOF
Range("A1").Select
ActiveCell = rs.Fields("Headings")
rs.MoveNext
Loop
rs.Close
oConn.Close
Set oConn = Nothing
Set rs = Nothing
End Sub
Doing the similar things in PHP, I could successfully log in to the MySQL server.
I have installed the ODBC connector.
But in the above VBA codes, I failed.
An error turns up. (see the codes where the error exists)
$connect = mysql_connect("sql100.xtreemhost.com","xth_9595110","myPassword") or die(mysql_error());
mysql_select_db("myTable",$connect);
This piece of vba worked for me:
Sub connect()
Dim Password As String
Dim SQLStr As String
'OMIT Dim Cn statement
Dim Server_Name As String
Dim User_ID As String
Dim Database_Name As String
'OMIT Dim rs statement
Set rs = CreateObject("ADODB.Recordset") 'EBGen-Daily
Server_Name = Range("b2").Value
Database_name = Range("b3").Value ' Name of database
User_ID = Range("b4").Value 'id user or username
Password = Range("b5").Value 'Password
SQLStr = "SELECT * FROM ComputingNotesTable"
Set Cn = CreateObject("ADODB.Connection") 'NEW STATEMENT
Cn.Open "Driver={MySQL ODBC 5.2.2 Driver};Server=" & _
Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
rs.Open SQLStr, Cn, adOpenStatic
Dim myArray()
myArray = rs.GetRows()
kolumner = UBound(myArray, 1)
rader = UBound(myArray, 2)
For K = 0 To kolumner ' Using For loop data are displayed
Range("a5").Offset(0, K).Value = rs.Fields(K).Name
For R = 0 To rader
Range("A5").Offset(R + 1, K).Value = myArray(K, R)
Next
Next
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub
Ranjit's code caused the same error message as reported by Tin, but worked after updating Cn.open with the ODBC driver I'm running. Check the Drivers tab in the ODBC Data Source Administrator. Mine said "MySQL ODBC 5.3 Unicode Driver" so I updated accordingly.
Just a side note for anyone that stumbles onto this same inquiry... My Operating System is 64 bit - so of course I downloaded the 64 bit MySQL driver... however, my Office applications are 32 bit... Once I downloaded the 32 bit version, the error went away and I could move forward.
Updating this topic with a more recent answer, solution that worked for me with version 8.0 of MySQL Connector/ODBC (downloaded at https://downloads.mysql.com/archives/c-odbc/):
Public oConn As ADODB.Connection
Sub MySqlInit()
If oConn Is Nothing Then
Dim str As String
str = "Driver={MySQL ODBC 8.0 Unicode Driver};SERVER=xxxxx;DATABASE=xxxxx;PORT=3306;UID=xxxxx;PWD=xxxxx;"
Set oConn = New ADODB.Connection
oConn.Open str
End If
End Sub
The most important thing on this matter is to check the proper name and version of the installed driver at:
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers\
Enable Microsoft ActiveX Data Objects 2.8 Library
Dim oConn As ADODB.Connection
Private Sub ConnectDB()
Set oConn = New ADODB.Connection
oConn.Open "DRIVER={MySQL ODBC 5.1 Driver};" & _
"SERVER=localhost;" & _
"DATABASE=yourdatabase;" & _
"USER=yourdbusername;" & _
"PASSWORD=yourdbpassword;" & _
"Option=3"
End Sub
There rest is here: http://www.heritage-tech.net/908/inserting-data-into-mysql-from-excel-using-vba/
Just to update this further
instead of looping through every row and column which takes forever.
try using
`Sub connect()
Dim Password As String
Dim SQLStr As String
'OMIT Dim Cn statement
Dim Server_Name As String
Dim User_ID As String
Dim Database_Name As String
'OMIT Dim rs statement
Set rs = CreateObject("ADODB.Recordset") 'EBGen-Daily
Server_Name = "Server_Name "
Database_Name = "Database_Name" ' Name of database
User_ID = "User_ID" 'id user or username
Password = "Password" 'Password
SQLStr = "SELECT * FROM item"
Set Cn = CreateObject("ADODB.Connection") 'NEW STATEMENT
Cn.Open "Driver={MySQL ODBC 8.0 ANSI Driver};Server=" & _
Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
rs.Open SQLStr, Cn, adOpenStatic
Range("A2").CopyFromRecordset rs
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub
this is multiple minutes faster