I've just started looking into interacting with an SQL database via Excel VBA, and I started off with the basic connection code from MSDN:
Sub GetDataFromADO()
'Declare variables'
Set objMyConn = New ADODB.Connection
Set objMyRecordset = New ADODB.Recordset
Dim strSQL As String
'Open Connection'
objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=fatcoin;User ID=root;Password=root;"
objMyConn.Open
'Set and Excecute SQL Command'
strSQL = "select * from productlist"
'Open Recordset'
Set objMyRecordset.ActiveConnection = objMyConn
objMyRecordset.Open strSQL
'Copy Data to Excel'
ActiveSheet.Range("A1").CopyFromRecordset (objMyRecordset)
End Sub
The issue I'm having is while I have an SQL instance running on my machine, on port 3306, which I can access using for example, HeidiSQL, every time I run this code I get an error message:
[DBNETLIB][ConnectionOpen (Connect()).]SQL Server does not exist or access denied
I have also tried adding a port:
objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost,3306;Initial Catalog=fatcoin;User ID=root;Password=root;"
And other such things. I can't see any reason it shouldn't work, but I haven't played with this much at all. I've tried searching through other threads to no avail.
Any ideas?
I am working with Excel 2010, on a 64-bit Machine, using MySQL 5.7
I should mention the above coding is being inputted into the "Module1" section of the VBAProject on Excel.
Thanks
Thanks for the answers.
I solved my own question via a helpful link I found that suggested I go into ODBC 32-bit (because Excel is 32-bit) and create a System DSN. Then, I used the connections string below:
objMyConn.ConnectionString = "Provider=MSDASQL.1;Persist Security Info=False;User ID=root;Data Source=localhost;Initial Catalog=fatcoin"
It worked a treat.
Related
I'm trying to write a straightforward piece of code to connect to a MySQL database.
Sub DBConnection()
Dim conn As New ADODB.Connection
Dim connectionStr As String
connectionStr = "DRIVER={SQL SERVER} ;SERVER=localhost; database=sakila; uid=test1; pwd=123"
conn.Open connectionStr
conn.Close
MsgBox "Connected!"
End Sub
I am faced with this error when I run it:
I suspect the details I am providing in the connection may be incorrect but I'm not sure.
User and database name in the MySQL workbench:
Perhaps it's the server name but as I understand it being on my local machine it should be localhost.
Would appreciate any help on this, thanks!
I have the following MYSQL products installed
I have installed the 5.2 driver and followed the connection string for 5.2 from the website provided. The error is still persisting (see below). I'll keep googling but any help would be appreciated as I am very new to this.
My first stop for connection strings is connectionstrings.com, where you should e able to find a connection string that fits your MySQL version and your connection method.
The standard MySQL connection string is:
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
...and several others on the site for various situations.
I am using VB.NET to connect to a MySQL database.
I have the following code:
Public Function getListOfDatabase() As List(Of String)
Dim SQL As String = "select * from covenusers"
Dim output As New List(Of String)()
' Set the connection string in the Solutions Explorer/Properties/Settings object (double-click)
Using cn = New MySqlConnection("Server=server33.web-
hosting.com;Port=3306;Database=dbname;Uid=dbusername;
Pwd=password123;")
Using cmd = New MySqlCommand(SQL, cn)
cn.Open() 'this is where it breaks
' do stuff
End Using
End Using
Return output
End Function
I'm using Imports MySql.Data.MySqlClient for the MySQL handling. I get the exception: Unable to connect to any of the specified MySQL hosts.
I know my server address, username, database name, and password are all correct. What exactly am I connecting to here? Does it go through SSH or something else?
Apparently shared hosts do not allow you to connect to the MySQL database directly. I had to set up a SSHClient using Renci.SSHClient (google it) and port forward my database through that. What a pain smh
Hopefully this will help someone having the same issue.
Objective:
I'm trying to connect to a database (e.g. associated with a website hosted by goDaddy) via VBA; using MS Word. I would like to distribute the VBA code via a word template so that others can also connect to my database.
Current Understanding - Is it correct?
In order to connect to a remote mySQL database I MUST configure a ODBC Data Source using (for example) mySQL Connector/ODBC (available here)?
There seems to be a way to connect without using a DSN as suggested here.
Issue:
I have been trying to use the mySQL Connector tool and am attempting to configure it with the information I have at hand. Steps taken:
download connector tool from dev.mysql.com
Control Panel > System & Security > Administrative Tools > ODBC Data Sources 64 Bit
add host: www.mywebsite.com
add user: NameOfDataBaseUser
add pwrd: PWForUser
I get the impression that I am using the wrong credentials... I found some documentation that said a list of DataBases would be displayed if connection is successful. That suggests to me that I should be using credentials for a master user - which user would that be?
Disclaimer
I do plan to connect to an online DB via VBA, but suspect that it might be better to connect indirectly via a php web-page.
If anyone has thoughts on this (security, ease of deployment, other) please let me know, it would probably be a new question. Other disclaimer, I am highly INexperienced with databases but keen to learn - slowly ;-)
I am currently working on a project with Excel where I am successfully connecting to a remote MySQL database.
I am using the DSN-less approach and this could probably work well for you, too:
Set remoteCon = New ADODB.Connection
conStr = "DRIVER={MySQL ODBC 5.3 Unicode Driver};" & _
"SERVER=myhomepage.com;PORT=3306;DATABASE=mydb;" & _
"UID=username;PWD=secret"
remoteCon.Open conStr
remoteCon.Execute ("USE mydb;")
In order for this to work, you also have to add a reference (in VBA backend): Tools > References > Check "Microsoft ActiveX Data Objects x.x Library".
You also need to have the MySQL ODBC Driver (in my case "MySQL ODBC 5.3 Unicode Driver") installed on your computer.
Queries can then be executed like this:
Dim rs As ADODB.Recordset
Set rs = remoteCon.Execute("SELECT * FROM table")
If Not rs.BOF And Not rs.EOF Then
result = rs.GetRows
End If
How to connect VBA to a Remote mySQL DataBase using ODBC
Thanks to #EVilliger & #tobifasc for your help with this, there are many 'how to configure mySQL questions' floating around but none that solved my (larger) issue.
Basic problem - my host does NOT allow remote connections to the database, except for from a single white-listed IP (this seems fairly common).
Questions Answered:
It turns out that you do NOT need to configure the mySQL connection using the connector, however you DO NEED to have an appropriate ODBC driver installed. The connector (with the driver) can be found here: https://dev.mysql.com/downloads/connector/odbc/
I uninstalled the mySQL Connector and everything seemed to continue working, until it didn't. Conclusion don't uninstall the mySQL Connector unless you have something to replace it with.
The credentials to use can be for a database user, not some elevated user.
For anyone interested in setting up and experimenting with mySQL from VBA here is a way forward:
Download & install the drivers (see above) - if the install fails you may need to install vcredist_x64.exe
Set-up a free mySQL database, I used HelioHost: https://www.heliohost.org/ (they will also give you a domain)
Create a database & user in HelioHost cPanel
Configure remote access - use wildcard % to allow all IPs
Add user to database
Use the following code to connect...
Code from accepted answer:
Sub connect2OnlineSQL()
' Note: add referecne to Microsoft ActiveX Data Objects #.# Library
' Tools > References > (scroll down...)
Set remoteCon = New ADODB.Connection
conStr = "DRIVER={MySQL ODBC 5.3 Unicode Driver};" & _
"SERVER=something.heliohost.org;PORT=3306;DATABASE=db_name;" & _
"UID=db_user;PWD=yourPassWordHere"
remoteCon.Open conStr
remoteCon.Execute ("USE db_name;")
End Sub
Thanks again :)
Following solution worked for me
Prerequisite:
Under Developer ->Tools->Reference Add the relevant Plug in for Oracle
Download and install ODBC Driver version for Oracle which you are using (32bit/64 bit)
Windows search -> ODBC Data Source -> Add Oracle driver under user DSN and System DSN
Copy paste below code which I used for MySQL and change the parameter based on your requirement
Sub ConnectToDB()
dbName = InputBox("Enter DB Name")
'Connection To MySQL
Dim oConn As ADODB.Connection
Dim str As String
str = "DRIVER={MySQL ODBC 8.0 Unicode Driver};SERVER=localhost;DATABASE=Employeeportal;PORT=3306;UID=root;PWD=root;"
Set oConn = New ADODB.Connection
oConn.Open str
MsgBox "Connected to MySQL DB"
'Exporting result set to Excel
Dim query As String
query = "select * from " & dbName
Dim recordSet As New ADODB.recordSet
recordSet.Open query, oConn
Sheet1.Range("A1:D1").CopyFromRecordset recordSet
oConn.Close
End Sub
I am working with LotusScript and trying to integrate my legacy project with MySQL.
I have done this many times with other MySQL databases and everything worked fine till now.
Using MySQL-ODBC driver v.5.3 MySQL ODBC Unicode driver.
But in my new task I am trying to connect to another remote mysql database.
(I am saying again that everything is working fine with other databases)
My connection-test code:
Dim mysqlConnection As New ODBCConnection
Dim sqlQuery As New ODBCQuery
Dim result As New ODBCResultSet
Dim selectAllQuery As String
Dim doc As NotesDocument
Dim session As New NotesSession
Dim generalDb As NotesDatabase
On Error Goto errblock
Set generalDb = session.CurrentDatabase
Call mysqlConnection.ConnectTo("Syncronization_agent","root","111111")
If Not mysqlConnection.IsConnected Then
Print "Connection is not working! Try again later!"
Exit Sub
Else
Print "Success connection to MySQL database - temp_data_db!"
End If
Set sqlQuery.Connection = mysqlConnection
Set result.Query = sqlQuery
selectAllQuery = "SELECT * FROM temp_data_db.temp_data_table WHERE id != ''"
sqlQuery.SQL = selectAllQuery
result.Execute
result.Close(DB_CLOSE)
mysqlConnection.Disconnect
errblock:
If Cstr(Err) Then
Print Cstr(Err) + " Message: " + Cstr(Error)
If result.GetError <> DBstsSuccess Then
result.Close(DB_CLOSE)
Messagebox result.GetErrorMessage + Chr(13) + result.GetExtendedErrorMessage
mysqlConnection.Disconnect
Exit Sub
End If
End If
I am getting this, none-typical, error:
I have debugged this code and this error comes in line with connectTo.
1. I have checked the ODBC driver connection-test and it outputs that connection to database is successful.
2. Tryed to run sql queries from MySQL Workbench to this database - SELECT,INSERT,UPDATE is working. (but in Workbench when I am trying to get db info and getting this errors (maybe this can create some problems or not..):
Question:
How to fix this issue? Is there some solutions for this? Or some thoughts?
For me this looks like a permission issue. I would try to fix the permissions for the user used - as soon as browsing the catalog works for that user inside MySql Workbench, I'm pretty sure that the error will disappear.
I guess while establishing the connection various database properties are queried, including schema and catalog information and that fails due to missing permissions.
I have solved this issue!
The problem wasn't in access or in the code!
The problem occurs when I was creating my ODBC connection in Windows system with the long name!
When I have changed the ODBC connection name (in the ODBC Administation tool) for more short one - everything started to work fine.
p.s. I have tryed to rename this ODBC connection multiple times and had this error when the name was very long.
It has been a long time since using VB6 and I didn't use MySql or DSN connections then, but I'm working on a legacy application that uses these. When I try to open the connect I am getting a
Data source not found and no default driver specified with this code
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim sql As String
Set rs = New ADODB.Recordset
Set cmd = New ADODB.Command
Set conn = New ADODB.Connection
conn.Open "DSN=AddressHealthcheck" '<- Fails on this statement
I have also tried specifying the DSN in the conn.ConnectionString but get the same error.
The AddressHealthcheck exists in the local System DSN, uses the MySql ODBC 5.1 Driver and connects successfully when tested.
I'm sure (and hope) I missing something obvious. Any suggestions?
Thanks,
Kevin
I use a DSN-less ODBC stored in a UDL. It's basically a file with a connection string in it. Maybe the connection string will be of use. Here's an example:
[oledb]
; Everything after this line is an OLE DB initstring
Provider=MSDASQL.1;Persist Security Info=True;Extended Properties="Driver=MySQL ODBC 5.1 Driver;SERVER=mysqlsvr;UID=userid;PWD=password;DATABASE=mydatabase;PORT=3306;OPTION=18475";Initial Catalog=mydatabase
rags comment (above) wasn't the solution, but it definitely helped track it down.
When using a full connection string the error message was different and much more useful, the driver failed to load.
The issue seems to be that since I'm on a 64 bit machine it was the 64 bit driver. VB6 can't use the 64 bit driver and the 32 bit driver doesn't show up in the ODBC Connection Administrator on a 64 bit machine.
DSN is not an option in my machine.
There are two ODBC Admin tools in a 64-bit system. Run the 32-bit version. Or better yet drop ODBC and get an OLEDB Provider for MySQL.
I was researching this by 1 labour day (yesterday). Today I've realized some errors I had yesterday in order to have this working.
Dim conexion As New ADODB.Connection
conexion.ConnectionString = "DSN = yourDsnName"
conexion.open
Don't forget to...
Create a user in your mysql server that has all the priviledges you need.
Assign the server's name or ip from where it is going to connect to mysql
Create your dsn on the client machine with the correct options en test it.