I have this code here:
Sub Example()
Dim Conn As New Connection
Conn.ConnectionString = "Server=localhost;Port=3306;Database=testing;Uid=root;Pwd=test;"
Conn.Open
Dim rs As New Recordset
Dim sql As String
sql = "Select productcode from labels" 'put spec of desired table here
rs.Open sql, Conn
If Not rs.EOF Then
Range("a1").CopyFromRecordset rs
End If
rs.Close
Set rs = Nothing
Conn.Close
Set Conn = Nothing
End Sub
And get this error code:
run-time error -2147467259 (80004005)
How can I fix this? What I am trying to do is:
Export data from MYSQL to excel without using the add-in.
I needed to update ConnectionString with the valid Server, Database, User ID and password, as I'm using SQL server on my side.
Now, if I pause your code at sql = "Select productcode from labels" line and run it, the code will fail, highlight ConnectionString line and return the following error message:
Following the error message, I needed to specify the default driver to make the code run properly. In my case it looked like this:
Conn.ConnectionString = "Driver={SQL Server};Server=...
As you are using MySQL, I suggest trying one of the following (check ODBC version):
Driver={MySQL ODBC 5.2 UNICODE Driver};
Driver={MySQL ODBC 5.2 ANSI Driver};
Related
I have an Access database for a client who wants to connect to and query the database using vbscript (so they can automate without actually opening the Access 2000 MDB). I can't figure out how to make the database connection.
I've tried several scripts, using both DAO and OLEDB. Below I've pasted the closest I've got, using an ODBC File DSN (I'm afraid using a System DSN would require extra work on the client's end, I'm trying to keep it simple).
Set objConnection = CreateObject("ADODB.Connection")
Set objRecordset = CreateObject("ADODB.Recordset")
'ERROR OCCURS HERE
objConnection.Open "FileDSN=D:\RLS.dsn;"
objRecordset.CursorLocation = adUseClient
objRecordset.Open "SELECT County FROM CountyTBL" , objConnection, adOpenStatic, adLockOptimistic
Here is the contents of RLS.dsn (I created this using Windows Control Panel so I am confident it's correct):
[ODBC]
DRIVER=Microsoft Access Driver (*.mdb)
UID=admin
UserCommitSync=Yes
Threads=3
SafeTransactions=0
PageTimeout=5
MaxScanRows=8
MaxBufferSize=2048
FIL=MS Access
DriverId=25
DefaultDir=D:\
DBQ=D:\RLS_be.mdb
The error message I got (and this was similar with the other 2 scripts I tried as well) was:
"Line 5, Char 4 Error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified. Source: Microsoft OLE DB Provider for ODBC Drivers"
You can simply use ADO to connect to the file without setting up a DSN. This will be simpler for your client.
For Access 2000, 2002-2003 MDB, use the following connection string:
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\RLS_be.mdb"
For Access 2007, 2010, 2013 ACCDB:
"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=D:\RLS_be.accdb"
The overall connection code:
' Build connection string
Dim sConnectionString
sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\RLS_be.mdb"
' Create connection object
Dim objConnection
Set objConnection = CreateObject("ADODB.Connection")
' Open Connection
objConnection.open sConnectionString
' Get recordset from SQL query
Dim objRecordset
Dim sQuery
sQuery = "SELECT County FROM CountyTBL"
Set objRecordset = CreateObject("ADODB.Recordset")
objRecordset.CursorLocation = adUseClient
objRecordset.Open sQuery, objConnection, adOpenStatic, adLockOptimistic
Here is another version using the connection string for a MS-Access 2016 database. The example connects to the 'clients.accdb' database and retrieves the value of the 'ClientID' field of the record where the 'ClientName' is equal to 'Joe Smith', then it loops through the records returned by the SQL statement.
Note that the extra quotations in the SQL statement are used in order to handle the scenario in which the name might contain a single quot ('), for example O'Connor.
Dim oConn, oRS
Dim ClientName : ClientName = "Joe Smith"
Set oConn = WSH.CreateObject("ADODB.Connection")
oConn.Open "Provider=Microsoft.ACE.OLEDB.16.0; Data Source=C:\test\clients.accdb"
Set oRS = oConn.Execute("Select ClientID From Clients Where ClientName=""" & ClientName & """")
Do While Not(oRS.EOF)
'Do something with the record.
oRS.MoveNext
Loop
oRS.Close
oConn.Close
Actually I use a ODBC-Connection to connect Ms Acces to tables of a PostgreSQL-DB. I connect them by using the External Data/Import ODBC-Link command. It works fine.
But how can I use VBA to link my tables?
When using VBA to link a table with ODBC, you can add and APP= argument to specify an application name that will generally show in the properties of the connection on your database server.
For example, here is a sample ODBC Connection string for a linked table:
ODBC;Driver={SQL Server};Server=MyServer\SQLExpress;Database=MyDatabase;APP=My App Title;Trusted_Connection=Yes;
My App Title is the string that will be your Application Name for that connection.
Update 1 In response to further comment by the OP:
Here is sample code to link a table via ODBC in VBA. To facilitate this, you also should always delete the ODBC linked table each time before re-linking it to make sure that your options are respected, and that Microsoft Access updates the schema for the linked table. This example shows a connection string for a SQL Server database, so all you would need to change is the connection string for your PostgreSQL-DB. The remaining VBA code would be the same.
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim strConn As String
Dim ODBCTableName as String
Dim AccessTableName as String
Set db = CurrentDb()
ODBCTableName = "dbo.YourTable"
AccessTableName = "YourTable"
strConn = "ODBC;Driver={SQL Server};Server=YOURSERVER\SQLINSTANCE;Database=MYDATABASE;Trusted_Connection=No;UID=MyUserName;PWD=MyPassword"
db.TableDefs.Refresh
For Each tdf In db.TableDefs
If tdf.Name = AccessTableName Then
db.TableDefs.Delete tdf.Name
Exit For
End If
Next tdf
Set tdf = db.CreateTableDef(AccessTableName)
'===============================
'If your connection string includes a password
'and you want the password to be saved, include the following 3 lines of code
'to specify the dbAttachSavePWD attribute of the TableDef being created
'If you don't want to save the password, you would omit these 3 lines of code
'===============================
If InStr(strConn, "PWD=") Then
tdf.Attributes = dbAttachSavePWD
End If
tdf.SourceTableName = ODBCTableName
tdf.Connect = strConn
db.TableDefs.Append tdf
For some reason this code gives Run time error 3170 - Could not find installable ISAM. However, when you add ODBC; at the beginning of the connection string, then it works. So the connection string should look something like:
strConn = "ODBC;DRIVER={MySQL ODBC 5.2 Unicode Driver};" _
& "SERVER=servername;" _
& "DATABASE=databasename;" _
& "UID=username;PWD=password; OPTION=3"
Sub hh()
Dim sql As String
Dim rs As New ADODB.Recordset
Dim con As ADODB.Connection
Dim dbConnStr As String
dbConnStr = "Driver={MySQL ODBC 5.2 ANSI DRIVER}; SERVER=localhost; DATABASE=landscape; USER=root; PASSWORD=mypass;"
Set con = New ADODB.Connection
con.Open dbConnStr
sql = "SELECT '東京都' AS tokyou"
rs.Open sql, con
Debug.Print rs!tokyou
rs.Close
Set rs = Nothing
con.Close
Set con = Nothing
End Sub
Returns things like "東・ "
I've tried:
1. use adodb.stream to convert query string to utf8, or otherwise convert query result to unicode
2. excute "set names = unicode;" in query
3. add "charset=unicode;" in connection string while open database connection
but none of them works, could you please help me, thanks!
It looks like you are using UNICODE characters. Please note that the ODBC driver comes in two flavours: ANSI and UNICODE. The latter is more appropriate to your situation. Use MySQL ODBC UNICODE Driver and you'll be good. Arigatou!
I wrote the following VBA code in Excel 2000 to create a connection to an Access 2000 with workgroup security in WindowsXP. Everything was working properly until we moved to Windows7 The database is still in Access2000.
It seems that the password value is eliminated from the ADODB connection string after opening a connection to the database. The first debug.print statement of the code below returns a string that contains the password and the user name but the second debug.print statement only shows the value of the User ID parameter. As a result when I try to create a recordset I get an error message that I do not have permission to the data.
Following the exact same procedure from Excel 2000 in Windows XP the ADODB connection string was not eliminating the password value and I was able to open a recordset.
Any suggestions?
Public Function sDbConnection() As String
Dim sString As String
Dim sConnection As String
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
conn.Provider = "Microsoft.Jet.OLEDB.4.0;"
' Provide path to the system Db
conn.Properties("Jet OLEDB:System database") = "S:\UTL\RscMgmt\SECURE.MDW"
' Username and password to the secured access database
conn.Properties("Password") = "MyPassword"
conn.Properties("User Id") = "MyUserID"
Debug.Print conn.ConnectionString
' Open a connection to the Access 2000 db and return the connection string
conn.Open "Data Source=" & "S:\UTL\RscMgmt\GasPortfolio 2000.mdb" & ";"
sConnection = conn.ConnectionString
Debug.Print sConnection
sDbConnection = sConnection
End Function
If you are on a 64 bit version of Win 7, the Microsoft.Jet.OLEDB.4.0 provider will not work, as it is only for 32-bit systems.
This website lists a few work-arounds you can implement.
Try it with "Microsoft.ACE.OLEDB.12.0" provider .
I'd like to find a simple example of working with remote MySQL base. I know, there are some tutorial over the internet, explaining how to set up ADODB.Connection and connectionstrings, but I couldnt make it work. Thanks for any help!
Download the ODBC connector from the MySQL download page.
Look for the right connectionstring over here.
In your VB6 project select the reference to Microsoft ActiveX Data Objects 2.8 Library. It's possible that you have a 6.0 library too if you have Windows Vista or Windows 7. If you want your program to run on Windows XP clients too than your better off with the 2.8 library. If you have Windows 7 with SP 1 than your program will never run on any other system with lower specs due to a compatibility bug in SP1. You can read more about this bug in KB2517589.
This code should give you enough information to get started with the ODBC connector.
Private Sub RunQuery()
Dim DBCon As adodb.connection
Dim Cmd As adodb.Command
Dim Rs As adodb.recordset
Dim strName As String
'Create a connection to the database
Set DBCon = New adodb.connection
DBCon.CursorLocation = adUseClient
'This is a connectionstring to a local MySQL server
DBCon.Open "Driver={MySQL ODBC 5.1 Driver};Server=localhost;Database=myDataBase; User=myUsername;Password=myPassword;Option=3;"
'Create a new command that will execute the query
Set Cmd = New adodb.Command
Cmd.ActiveConnection = DBCon
Cmd.CommandType = adCmdText
'This is your actual MySQL query
Cmd.CommandText = "SELECT Name from Customer WHERE ID = 1"
'Executes the query-command and puts the result into Rs (recordset)
Set Rs = Cmd.Execute
'Loop through the results of your recordset until there are no more records
Do While Not Rs.eof
'Put the value of field 'Name' into string variable 'Name'
strName = Rs("Name")
'Move to the next record in your resultset
Rs.MoveNext
Loop
'Close your database connection
DBCon.Close
'Delete all references
Set Rs = Nothing
Set Cmd = Nothing
Set DBCon = Nothing
End Sub