EXCEL VBA: trying to write a table in MySQL Database - mysql

I´m trying to write a table into a MySQL Database, ich searched for many Examples but id didn´t working and i hav no idea why.
my Code:
Private Sub abfrage()
Dim xlsstring As String
Dim xlsrecordsetarray
Dim xlsadodbconnection As New ADODB.Connection
Dim xlsrecordset As New ADODB.Recordset
Dim xlssource As String
Dim xlsconnect As String
Dim sqlstring As String
Dim sqlrecordsetarray
Dim sqladodbconnection As New ADODB.Connection
Dim sqlrecordset As New ADODB.Recordset
Dim sqlsource As String
Dim sqlconnect As String
xlssource = ThisWorkbook.FullName
'xlssource ="C:\mappe1.xls"
'SQL Verbindung für Exceldatei als Quelle
xlsconnect = "PROVIDER=MSDASQL.1;" & _
"DSN=Excel Files;" & _
"DBQ=" & xlssource & ";" & _
"HDR=Yes;"
sqlconnect = "DRIVER={MySQL ODBC 5.3 Driver};" & _
"DATA SOURCE=MySQL ODBC;" & _
"SERVER=localhost;" & _
"PORT=3306;" & _
"UID=root;" & _
"PWD=root;" & _
"DATABASE=test;"
xlsadodbconnection.Open xlsconnect
sqladodbconnection.Open sqlconnect
sqlstring = "INSERT INTO test (ID, text) SELECT id, text FROM [Tabelle1$]"
sqlrecordset.Open sqlstring, sqladodbconnection
xlsrecordset.Close
xlsadodbconnection.Close
sqladodbconnection.Close
End Sub
it shows me the error:
[MySQL[ODBC 5.3(w) Driver][mysqld-5.6.16]You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[Tabelle1$]' at Line 1
please, can anyone help me?
Thanks

What is the name of the table [Tabelle1$] in MySQL? Are you adding the "[" and "]" vba-style?
If so, try removing those and running your query again.
edited per comments:
Save your spreadsheet as a .CSV and try using the "LOAD DATA INFILE LOCAL" command to move the data into a temp table on your MySQL server.
http://www.experts-exchange.com/Programming/Languages/.NET/Visual_Basic.NET/Q_26714181.html

Related

Connecting to MySQL server from excel with VBA code

I'm running a MySQL server on my old computer and trying to connect it from my current computer. I would like to access to the server from Excel but I keep getting the error:
'[Microsoft] [ODBC Driver Manager] Data source name not found and no default driver specified'
I've downloaded a 'MySQL connector ODBC 8.0.20 win 32' which should match my computer requirements. At this point I'm quite clueless why I keep getting the error. Please find my VBA code below.
Private Sub Data_to_SQL_Click()
Dim con As ADODB.Connection
Set con = New ADODB.Connection
Dim strConn As String
strConn = "Driver={MySQL ODCB 8.0 Unicode Driver};SERVER=(my old computer ip address);DATABASE=Database;USER=root;PASSWORD=(password)"
con.Open strConn
Dim rng As Range
Set rng = Application.Range("A2:E14")
Dim row As Range
For Each row In rng.Rowss
Dim Sql As String
Sql = "insert into kavijamaarat (pvm, ravintola, ruoka, hinta, kpl) values ('" & row.Cells(1).Value & "', '" & row.Cells(2).Value & "', '" & row.Cells(3).Value & "', '" & row.Cells(4).Value & "', '" & row.Cells(5).Value & "')"
con.Execute Sql
Next row
con.Close
MsgBox "Done"
End Sub
Rewrite
strConn = "Driver={MySQL ODCB 8.0 Unicode Driver};SERVER=(my old computer ip address);DATABASE=Database;USER=root;PASSWORD=(password)"
to
strConn = "Driver={MySQL ODBC 8.0 Unicode Driver};SERVER=(my old computer ip address);DATABASE=Database;USER=root;PASSWORD=(password)"

MS Excel has stopped working during a query (by using vba) in MySQL database

After connecting to MySQL and perform a database query (via VBA), Excel crashes when I try to assign a variable to the elements of the resultset.
It worked fine at the beginning, but then suddenly it stopped to work.
Excel 2016. MySql 5.1.35 Community Server (GPL)
Sub doSomething()
call conectBD
Dim cSQL as String
Dim rstSet as RecordSet
Dim myName as String
cSQL = "SELECT name FROM tbNames WHERE id_name=3"
Set rstSet = New ADOBD.Recordset
rstSet.Open cSQL, conexao, adOpenStatic, adLockReadOnly
myName = rstSet!name 'Excel crashes here'
rstSet.Close
Set rstSet = Nothing
call disconectBD
end Sub
'Connect to BD'
sub conectBD()
Set conexao = New ADODB.Connection'Connection'
conexao.ConnectionString = "DRIVER={MySQL ODBC 5.1 Driver};" _
& "SERVER=localhost;" _
& "DATABASE=DB;" _
& "UID=user;" _
& "PASSWORD=password"
conexao.Open
End sub
'Disconnet to BD'
sub disconectBD()
conexao.close
set conexao = nothing
end sub
I expect it works just like it did at the beginning.

Excel Vba Problems deleting rows from mysql database

Hi I'm trying to delete all the rows in mysql database, using vba in excel.
I have tried a lot of codes now and the closest I get, is the following code but I still get an syntax error in :
rsmysql.Open rsstr, coninc
Can someone help me correct the code, so I can get it to work please.
Dim rsmysql As ADODB.Recordset 'Holds records
Dim rsstr As String
Dim coninc As String
Set cnmysql = New ADODB.Connection
Set rsmysql = New ADODB.Recordset
coninc = "Driver={MySQL ODBC 5.3 ANSI Driver};Server=" & _
Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
rsstr = "delete * from TLHMember_List;"
cnmysql.Open coninc
rsmysql.Open rsstr, coninc
MsgBox "Data has been deleted"
Exit Sub
rsstr = "delete from TLHMember_List"
cnmysql.Open coninc
cnmysql.Execute rsstr
MsgBox "Data has been deleted"

How do I setup an ADODB connection to SQL Server 2008 in Microsoft Access 2010?

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

VBA Connect to MYSQL

I am trying to setup a remote database connection to a server running MySQL version 5.0.96. When I execute I get the following error.
Any assistance is appreciated.
Here is my connection code:
Public Function opendb()
Dim oConn As ADODB.Connection
Dim Server_Name As String
Dim User_Name As String
Dim Password As String
Dim Database_Name As String
Server_Name = Sheets("_config").Range("B2").value
User_Name = Sheets("_config").Range("B3").value
Password = Sheets("_config").Range("B4").value
Database_Name = Sheets("_config").Range("B5").value
Set oConn = New ADODB.Connection
oConn.Open "DRIVER={MySQL ODBC 5.0.96 Driver};" & _
"SERVER=Server_Name;" & _
"DATABASE=Database_Name;" & _
"USER=User_Name;" & _
"PASSWORD=Password;" & _
"Option=3"
End Function
Dim oConn As ADODB.Connection
Dim Server_Name As String
Dim User_Name As String
Dim Password As String
Dim Database_Name As String
Server_Name = Sheets("_config").Range("B2").value
User_Name = Sheets("_config").Range("B3").value
Password = Sheets("_config").Range("B4").value
Database_Name = Sheets("_config").Range("B5").value
Set oConn = New ADODB.Connection
oConn.Open "DRIVER={MySQL ODBC 5.0.96 Driver};" & _
"SERVER=" & Server_Name & ";" & _
"DATABASE=" & Database_Name & ";" & _
"USER=" & User_Name & ";" & _
"PASSWORD=" & Password & ";" & _
"Option=3"
There might be other problems with your drivers but when I tested the code you posted on my end I got the same error - it's not going to read your variables unless you concat them
Edit - I'm using a 5.2a server - when I try to connect using 5.0.96 I get the same error again , but of course using the 5.2a driver in the connection string works fine. So you will probably need to download the 5.0.96 driver specifically. I did a little searching and couldnt find it, I'll keep looking around for a minute
MySQL server is running 5.0.96. DO NOT INSTALL MySQL Connector/ODBC 5.2.6. This driver is NOT backwards compatible from VBA. If you have it installed and you are having the same problem I did do the follow:
1) FIRST remove any User & System Data Sources you have added
2) Uninstall all ODBC 5.2 drivers
3) Installed Connector/ODBC 3.51.30. (You May Need to Reboot)
4) Make your Connection String > DRIVER={MySQL ODBC 3.51 Driver};
Hope this saves you lots of time.
You may write Set oConn = CreateObject("ADODB.Connection") 'NEW STATEMENT
instead of Set oConn = New ADODB.Connection