create mysql database with vba - mysql

I use VBA mostly to access MySQL database and to downlaod data from the database into an excel worksheet. In order to open connection to MySQL server through vba i use the following code:
Public Sub OpenConnection()
Set conn = New ADODB.Connection
conn.Open GetConnectionString()
End Sub
Function GetConnectionString() As String
Dim ConnectionString$
ConnectionString$ = "DRIVER={MySQL ODBC 5.3 UNICODE Driver}; _
SERVER=localhost;DATABASE=test;USER=root;PASSWORD=google;Option=3"
GetConnectionString = ConnectionString$
End Function
my question is that is there a VBA code i can use to create a new database in MySQL server and give it a specified name?
my MySQL server is version 5.6 if it helps.

thanks for the comment Drew, I actually have other codes that enable me to enter query to MySQL database, the only this that was missing is the query to create a database if the database does not exits, anyways here is the whole code in order to create a MySQL database with VBA:
Sub create_database()
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Call OpenConnection
Dim RS As ADODB.Recordset
Set RS = New ADODB.Recordset
Dim Query$
Query$ = "CREATE DATABASE IF NOT EXISTS Database_name"
RS.Open Query$, conn
Set RS = Nothing
Call CloseConnection
End Sub
Public Sub OpenConnection()
Set conn = New ADODB.Connection
conn.Open GetConnectionString()
End Sub
Function GetConnectionString() As String
Dim ConnectionString$
ConnectionString$ = "DRIVER={MySQL ODBC 5.3 UNICODE Driver}; _
SERVER=localhost;DATABASE=test;USER=root;PASSWORD=google;Option=3"
GetConnectionString = ConnectionString$
End Function
Public Sub CloseConnection()
conn.Close
Set conn = Nothing
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

Extract values from mySQL database into Excel using VBA

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

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

MySQL query error (ODBC 3.51)

I'm trying to execute query in a VB6 app.
Here is my code:
Dim con As ADODB.Connection
Set con = New ADODB.Connection
con.ConnectionString = "Driver={MySQL ODBC 3.51 Driver}; Server=***; Database=***; Username=***; Password=***; Option=3"
con.Open
Dim cmd As New ADODB.Command
With cmd
.ActiveConnection = con
.CommandText = "SELECT COD_CONFIG FROM FDT_CONFIG"
.CommandType = adCmdText
End With
Dim rs As New ADODB.Recordset
rs.CursorLocation = adUseClient
rs.Open cmd, , adOpenStatic, adLockOptimistic
I've hidden some information in the connection string but in my app I'm using the correct values.
I can successfully open the connection, but when I try to execute the query I get:
"Execution error '2147467259 (800004005)' : unspecified error"
Can someone tell me where I'm going wrong?
If you want to assign a Command object's ActiveConnection to an existing Connection object, you must use Set:
With cmd
Set .ActiveConnection = con
....
End With
It's a little confusing because you can also assign a string to the ActiveConnection property and ADO will create an ad-hoc connection for you. In that case, you wouldn't use Set because you're just assigning a value to an intrinsic type (string):
With cmd
.ActiveConnection = "Driver={MySQL ODBC 3.51 Driver}; Server=***; Database=***; Username=***; Password=***; Option=3"
...
End With
So the property can be used multiple ways. In your scenario, however, since you're assigning an object reference, you'll need to use the Set keyword.

Select query run from VBA using ADO.RecordSet object does not return a complete result

I have a MySQL DB on Localhost, which I wish to access from VBA.
I have set up the ODBC connection to MySQL, and I am able to query results.
Presently, the MySQL table has 2 rows of data which should be returned. But the "Items" in "Recordset.Fields" is retaining only the last row.
My code is as follows
Public Sub Query_()
Dim connection As connection
Set connection = OpenConnection()
' Create a record-set that holds all the tasks
Dim records As ADODB.Recordset
Set records = New ADODB.Recordset
Call records.Open("SELECT pk_Client, PAN_Client FROM client", connection)
Dim result() As String
For Each Item In records.Fields
MsgBox (Item.OriginalValue)
Next
connection.Close
End Sub
Here is the OpenConnection UDF:
Private Function OpenConnection() As ADODB.connection
'Read type and location of the database, user login and password
Dim source As String, location As String, user As String, password As String
source = "taskman"
location = "localhost"
user = "root"
password = ""
'Build the connection string depending on the source
Dim connectionString As String
connectionString = "Driver={MySQL ODBC 5.3 Unicode Driver};Server=" & location & ";Database=taskman;UID=" & user & ";PWD=" & password
'Create and open a new connection to the selected source
Set OpenConnection = New ADODB.connection
Call OpenConnection.Open(connectionString)
End Function
Please help me in figuring out why the entire query result is not being retained.
Thanks
-Chinmay Kamat
This is how you'd typically code this sort of operation:
Public Sub Query_()
Dim conn As ADODB.Connection
Dim records As ADODB.Recordset, fld As ADODB.Field
Set conn = OpenConnection()
Set records = New ADODB.Recordset
records.Open "SELECT pk_Client, PAN_Client FROM client", conn
'check you got any records
If Not records.EOF Then
'loop over records
Do While Not records.EOF
Debug.Print "-------------------------"
For Each fld In records.Fields
Debug.Print fld.Name, fld.OriginalValue
Next
records.movenext 'next record
Loop
End If
records.Close
conn.Close
End Sub