I would like to write a macro in Excel that will write to a mysql database. Can someone please get me started on this?
You can connect to MySQL with a connection string and ADO:
''http://support.microsoft.com/kb/246335
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
strCon = "Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=MyDB;" _
& "User=root;Password=pw;Option=3;"
cn.Open strCon
You can also use DSN with a connection to Excel using the Jet driver:
Dim cn As ADODB.Connection
''Not the best way to get the name, just convenient for notes
strFile = Workbooks(1).FullName
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
Set cn = CreateObject("ADODB.Connection")
''For this to work, you must create a DSN and use the name in place of
''DSNName
strSQL = "INSERT INTO [ODBC;DSN=DSNName;].NameOfMySQLTable " _
& "Select AnyField As NameOfMySQLField FROM [Sheet1$];"
cn.Execute strSQL
Writing to a mysql database is no different to writing to any other database.
You'd create an ADODB.Connection object, .Open it with an appropriate connection string and use the .Execute method (or ADODB.Command) to execute sql.
See http://msdn.microsoft.com/en-us/library/ms807027.aspx for more information.
You'd have to a have a mysql access driver installed (ODBC or OLEDB) and reference the Microsoft ActiveX Data Objects 2.8 from your vba project.
Related
I'm hosting the MySQL database in Heroku. I created a connection from Excel with 'MySQL for Excel' add-in, but I want to establish a connection from Excel with VBA code.
I get
Access denied for user 'user' to database 'database'
My VBA code, but I think the reason for the error is somewhere else (privileges, database settings, etc... ).
Dim con As ADODB.Connection
Set con = New ADODB.Connection
Dim strConn As String
strConn = "Driver={MySQL ODBC 8.0 Unicode Driver};SERVER=serverName;DATABASE=databaseName;USER=username;PASSWORD=password"
con.Open strConn
For exammple, here is a piece of code by using mariaDB, btw you have to install corresponding driver for database:
host_address = "xxx.xxx.xxx.xxx"
Set conn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
conn.ConnectionString = "DRIVER={MariaDB ODBC 3.0 Driver};" _
& "SERVER=" & host_address & ";" _
& " DATABASE=databasename;" _
& "UID=username;PWD=password; OPTION=3"
conn.Open
strSQL ="....."
....
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.
I'm trying to select rows in a MySQL database using Excel Macros. The connection appears to be working OK but I get a VBA 3001 error
(Microsoft visual basic 3001 arguments are of the wrong type, or are out of acceptable range, or are in conflict with one another)
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Dim oConn As ADODB.Connection
Set oConn = New ADODB.Connection
oConn.Open "DRIVER={MySQL ODBC 5.2 Unicode Driver};" & _
"SERVER=localhost;" & _
"DATABASE=talar;" & _
"USER=root;" & _
"PASSWORD=root;" & _
"Option=3"
strSQL = "SELECT * FROM ots where Estado in (2,3)"
rs.Open SQLStr, Cn, adOpenForwardOnly, adLockReadOnly
Dim myArray()
myArray = rs.GetRows()
oConn.Close
MySQL ODBC 5.2 Unicode Driver is installed, MySQL service is running fine, I am using Excel 2010, windows 7. anyone have any idea? thanks!
You've actually got two problems both of which would be easier to spot of you were using Option Explicit.
Both are in this line:
rs.Open SQLStr, Cn, adOpenForwardOnly, adLockReadOnly
Your SQL string variable is strSQL and your connection object is oConn. So change the line of code to:
rs.Open strSQL, oConn, adOpenForwardOnly, adLockReadOnly
Im trying to insert a row in a mysql db using Excel Macros. The connection appears to be working OK but i get a vba 3001 error
(Microsoft visual basic 3001 arguments are of the wrong type, or are out of acceptable range, or are in conflict with one another)
when y execute this code:
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
ConnectDB
'strSQL = "INSERT INTO talar.ots (UbicacionTecnica, Equipo, Posmant) VALUES ('sdasd', 'sdasd','sdasd')"
rs.Open strSQL, oConn, adOpenDynamic, adLockOptimistic
I allready read and try different things with 50 tutorials and other posts in this page, all bad results....
this is the code of the connection:
Private Sub ConnectDB()
Dim oConn As ADODB.Connection
Set oConn = New ADODB.Connection
oConn.Open "DRIVER={MySQL ODBC 5.2 Unicode Driver};" & _
"SERVER=localhost;" & _
"DATABASE=talar;" & _
"USER=root;" & _
"PASSWORD=root;" & _
"Option=3"
End Sub
MySQL ODBC 5.2 Unicode Driver is installed, mysql service is running fine, I am using Excel 2010, windows 7. I dont know if this information is enough.
anyone have any idea?
thanks!
oConn is local to the ConnectDB sub so you are passing nothing to the recordsets Open.
Add Option Explicit to the top of your code file to receive a warning when you do something like this.
Make a function that returns the connection:
Private Function ConnectDB() As ADODB.Connection
Set ConnectDB = New ADODB.Connection
ConnectDB.Open "DRIVER={MySQL ODBC 5.2 Unicode Driver};SERVER=localhost;DATABASE=talar;USER=root;PASSWORD=root;Option=3"
End Function
Then
dim cn as ADODB.Connection
set cn = ConnectDB()
cn.Execute "INSERT INTO talar.ots (UbicacionTecnica, Equipo, Posmant) VALUES ('sdasd', 'sdasd','sdasd')"
cn.Close
You do not need a Recordset for an insert as no rows will be returned.
When you do need a Recordset adOpenForwardOnly, adLockReadOnly are better than adOpenDynamic, adLockOptimistic unless you specifically need the features offered by the latter.
I just installed SQL Server 2008 on my laptop. I also have Microsoft Access 2010 installed. Using VBA, I am trying to create an ADODB connection to my own database on SQL Server but I'm having trouble finding the right line of code:
When I use this below, it doesn't work.
The name of my computer is LAPTOPX and the database is HomeSQL.
I am sure it's super easy but since I'm just starting out I can't seem to find the right way to ask the question.
Thanks!
Dim DBCONT As Object
Set DBCONT = CreateObject("ADODB.Connection")
Dim strDbPath As String
strDbPath = "LAPTOPX/HomeSQL"
Dim sConn As String
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source =" & strDbPath & ";" & _
"Jet OLEDB:Engine Type=5;" & _
"Persist Security Info=False;"
DBCONT.Open sConn
First, you need to make sure SQL Native Client is instaled. Reference
SQL Server 2008
Standard security
Provider=SQLNCLI10;Server=myServerAddress;Database=myDataBase;Uid=myUsername;
Pwd=myPassword;
Trusted connection
Provider=SQLNCLI10;Server=myServerAddress;Database=myDataBase;
Trusted_Connection=yes;
Connecting to an SQL Server instance
The syntax of specifying the server instance in the value of the server key is the same for all connection strings for SQL Server.
Provider=SQLNCLI10;Server=myServerName\theInstanceName;Database=myDataBase;
Trusted_Connection=yes;
Source
Dim conn As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim sConnString As String
Dim recordsAffected as Long
'Create connection string
sConnString = "Provider=sqloledb; Server=LAPTOPX; Database=HomeSQL; Trusted_Connection=True;"
'Open connection and execute
conn.Open sConnString
'Do your query
With cmd
.ActiveConnection = conn
.CommandType = adCmdText
.CommandText = "Select ...;"
.Execute recordsAffected 'Includes a return parameter to capture the number of records affected
End With
Debug.Print recordsAffected 'Check whether any records were inserted
'Clean up
If CBool(conn.State And adStateOpen) Then conn.Close
Set cmd = Nothing
Set conn = Nothing
This connetion string works under Excel VBA. In MsAccess also should.
dbName = "test" 'your database name
dbFilePath = "C:\db.mdf" 'your path to db file
connStr = "Driver={SQL Server native Client 11.0};" & _
"Server=(LocalDB)\v11.0;" & _
"AttachDBFileName=" & dbFilePath & ";" & _
"Database=" & dbName & ";" & _
"Trusted_Connection=Yes"
Full solution: http://straightitsolutions.blogspot.com/2014/12/how-to-connect-to-sql-server-local.html