Excel Vba Problems deleting rows from mysql database - mysql

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"

Related

Exporting Data from Excel to phpmyadmin SQL database

I would appreciate some help solving problems accessing a MySQL database from Excel.
I've created the database in phpmyadmin. I've also been able to manually import data via a CSV file into the SQL database on phhpmyadmin.
So, I'm sure that I've got the right IP address, user ID and password for the database.
I've also read various posts about how to configure ODBC connections from Windows to SQL and I think I've followed the right instructions.
However, I can't seem to get the code to work from VBA. I keep getting various errors.
Here's the code I've been using, minus the actual database names and User IDs.
Private Sub cmdInsertData_Click()
Dim oConn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim Pwd As String
Dim SQLStr As String
Dim Svr_Nm As String
Dim UID As String
Dim Dbs_Nm As String
' Input Parameters
Pwd = "mypassword"
UID = "myuser"
srvr_nm = "xxx.xxx.xx.xx:yyyy"
Dbs_Nm = "myname"
Set rs = New ADODB.Recordset
Set oConn = New ADODB.Connection
SQLStr = "DRIVER={MySQL ODBC 5.3 ANSI Driver};"
SQLStr = SQLStr & "SERVER=" & srvr_nm & ";DATABASE=" & Dbs_Nm & ";USER=" & UID & ";PASSWORD=" & Pwd & ";Option=3"
oConn.Open SQLStr
MsgBox "Connected to " & Dbs_Nm & " via " & srvr_nm
End Sub
I've reset the code as follows. The error message is generated by the line "oConn.Open SQLStr". The error generated is
Run-time error ‘-2147467259 (80004005)’:
[MySQL][ODBC 5.3(a) Driver]Unknown MySQL server host ‘209.159.152.202:2083’ (0)
New Code:
Private Sub CheckConnection()
Dim oConn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim Pwd As String
Dim SQLStr As String
Dim Svr_Nm As String
Dim Usr_ID As String
Dim Dbs_Nm As String
' Input Parameters
Pwd = "mypassword"
Usr_ID = "myID"
srvr_nm = "209.159.152.202:2083"
Dbs_Nm = "mydatabase"
Set rs = New ADODB.Recordset
Set oConn = New ADODB.Connection
SQLStr = "DRIVER={MySQL ODBC 5.3 ANSI Driver};"
SQLStr = SQLStr & "SERVER=" & srvr_nm & ";DATABASE=" & Dbs_Nm & ";USER=" & Usr_ID & ";PASSWORD=" & Pwd & ";Option=3"
oConn.Open SQLStr
MsgBox "Connected to " & Dbs_Nm & " via " & srvr_nm
End Sub
Thanks for the suggestion about adding the Port= as a separate variable. I've tried that however (see new code) and it still doesn't work.
Private Sub CheckConnection()
Dim oConn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim Pwd As String
Dim SQLStr As String
Dim Svr_Nm As String
Dim Usr_ID As String
Dim Dbs_Nm As String
Dim Port_Nm As String
' Input Parameters
Pwd = "mypassword"
Usr_ID = "myID"
Svr_Nm = "209.159.152.202"
Dbs_Nm = "mydatabase"
Port_Nm = "2083"
Set rs = New ADODB.Recordset
Set oConn = New ADODB.Connection
SQLStr = "DRIVER={MySQL ODBC 5.3 ANSI Driver};"
SQLStr = SQLStr & "Server=" & Svr_Nm & ";Port=" & Port_Nm & ";Database=" & Dbs_Nm & ";User=" & Usr_ID & ";Password=" & Pwd & ";Option=3"
oConn.Open SQLStr
MsgBox "Connected to: " & Dbs_Nm & " via " & Svr_Nm
End Sub
I still get the same error message at the same place.

EXCEL VBA: trying to write a table in MySQL Database

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

Access VBA to update Access table from SQL Server table source

I have created the code below to test whether I can run a query and retrieve a data from an SQL server table. And so far I can return the result using a MessageBox, but somehow I just don't know how to use this connection to update the table inside this Access file. Basically I want to use this as a front end file. Then, when the form is open it will automatically update the table inside this access file and load the data to the combo box as a list. I tried searching it here and read many discussions here and in Google but currently I can't find the right solution.
Option Compare Database
Sub LocalServerConn_Test()
Set conn = New adodb.Connection
Set rst = New adodb.Recordset
strDBName = "DataSet"
strConnectString = "Provider = SQLOLEDB.1; Integrated Security = SSPI; " & _
"Initial Catalog = " & strDBName & "; Persist Security Info = True; " & _
"Worksation ID = abc123;"
conn.ConnectionString = strConnectString
conn.Open
strSQL = "SELECT DISTINCT dbo.abc.abc123 FROM dbo.abc"
rst.Open Source:=strSQL, ActiveConnection:=strConnectString, _
CursorType:=adOpenDynamic, LockType:=adLockOptimistic
If rst.RecordCount = 0 Then
MsgBox "No records returned"
Else
rst.MoveFirst
Do While Not rst.EOF
MsgBox rst.Fields("abc123").Value
rst.MoveNext
Loop
End If
conn.Close
rst.Close
End Sub
You should be able to use code very similar to this:
Dim cdb As DAO.Database
Set cdb = CurrentDb
cdb.Execute _
"DELETE FROM LocalTable", _
dbFailOnError
cdb.Execute _
"INSERT INTO LocalTable (abc123) " & _
"SELECT DISTINCT abc123 " & _
"FROM " & _
"[" & _
"ODBC;" & _
"Driver={SQL Server};" & _
"Server=.\SQLEXPRESS;" & _
"Database=DataSet;" & _
"Trusted_Connection=yes;" & _
"].[dbo.abc]", _
dbFailOnError
Set cdb = Nothing
You can just keep the combo box bound to [LocalTable] and the updated values from the SQL Server table should appear.

How can VBA connect to MySQL database in Excel?

Dim oConn As ADODB.Connection
Private Sub ConnectDB()
Set oConn = New ADODB.Connection
Dim str As String
str = "DRIVER={MySQL ODBC 5.2.2 Driver};" & _
"SERVER=sql100.xtreemhost.com;" & _
"PORT=3306" & _
"DATABASE=xth_9595110_MyNotes;" & _
"UID=xth_9595110;" & _
"PWD=myPassword;" & _
"Option=3"
''' error '''
oConn.Open str
End Sub
Private Sub InsertData()
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
ConnectDB
sql = "SELECT * FROM ComputingNotesTable"
rs.Open sql, oConn, adOpenDynamic, adLockOptimistic
Do Until rs.EOF
Range("A1").Select
ActiveCell = rs.Fields("Headings")
rs.MoveNext
Loop
rs.Close
oConn.Close
Set oConn = Nothing
Set rs = Nothing
End Sub
Doing the similar things in PHP, I could successfully log in to the MySQL server.
I have installed the ODBC connector.
But in the above VBA codes, I failed.
An error turns up. (see the codes where the error exists)
$connect = mysql_connect("sql100.xtreemhost.com","xth_9595110","myPassword") or die(mysql_error());
mysql_select_db("myTable",$connect);
This piece of vba worked for me:
Sub connect()
Dim Password As String
Dim SQLStr As String
'OMIT Dim Cn statement
Dim Server_Name As String
Dim User_ID As String
Dim Database_Name As String
'OMIT Dim rs statement
Set rs = CreateObject("ADODB.Recordset") 'EBGen-Daily
Server_Name = Range("b2").Value
Database_name = Range("b3").Value ' Name of database
User_ID = Range("b4").Value 'id user or username
Password = Range("b5").Value 'Password
SQLStr = "SELECT * FROM ComputingNotesTable"
Set Cn = CreateObject("ADODB.Connection") 'NEW STATEMENT
Cn.Open "Driver={MySQL ODBC 5.2.2 Driver};Server=" & _
Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
rs.Open SQLStr, Cn, adOpenStatic
Dim myArray()
myArray = rs.GetRows()
kolumner = UBound(myArray, 1)
rader = UBound(myArray, 2)
For K = 0 To kolumner ' Using For loop data are displayed
Range("a5").Offset(0, K).Value = rs.Fields(K).Name
For R = 0 To rader
Range("A5").Offset(R + 1, K).Value = myArray(K, R)
Next
Next
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub
Ranjit's code caused the same error message as reported by Tin, but worked after updating Cn.open with the ODBC driver I'm running. Check the Drivers tab in the ODBC Data Source Administrator. Mine said "MySQL ODBC 5.3 Unicode Driver" so I updated accordingly.
Just a side note for anyone that stumbles onto this same inquiry... My Operating System is 64 bit - so of course I downloaded the 64 bit MySQL driver... however, my Office applications are 32 bit... Once I downloaded the 32 bit version, the error went away and I could move forward.
Updating this topic with a more recent answer, solution that worked for me with version 8.0 of MySQL Connector/ODBC (downloaded at https://downloads.mysql.com/archives/c-odbc/):
Public oConn As ADODB.Connection
Sub MySqlInit()
If oConn Is Nothing Then
Dim str As String
str = "Driver={MySQL ODBC 8.0 Unicode Driver};SERVER=xxxxx;DATABASE=xxxxx;PORT=3306;UID=xxxxx;PWD=xxxxx;"
Set oConn = New ADODB.Connection
oConn.Open str
End If
End Sub
The most important thing on this matter is to check the proper name and version of the installed driver at:
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers\
Enable Microsoft ActiveX Data Objects 2.8 Library
Dim oConn As ADODB.Connection
Private Sub ConnectDB()
Set oConn = New ADODB.Connection
oConn.Open "DRIVER={MySQL ODBC 5.1 Driver};" & _
"SERVER=localhost;" & _
"DATABASE=yourdatabase;" & _
"USER=yourdbusername;" & _
"PASSWORD=yourdbpassword;" & _
"Option=3"
End Sub
There rest is here: http://www.heritage-tech.net/908/inserting-data-into-mysql-from-excel-using-vba/
Just to update this further
instead of looping through every row and column which takes forever.
try using
`Sub connect()
Dim Password As String
Dim SQLStr As String
'OMIT Dim Cn statement
Dim Server_Name As String
Dim User_ID As String
Dim Database_Name As String
'OMIT Dim rs statement
Set rs = CreateObject("ADODB.Recordset") 'EBGen-Daily
Server_Name = "Server_Name "
Database_Name = "Database_Name" ' Name of database
User_ID = "User_ID" 'id user or username
Password = "Password" 'Password
SQLStr = "SELECT * FROM item"
Set Cn = CreateObject("ADODB.Connection") 'NEW STATEMENT
Cn.Open "Driver={MySQL ODBC 8.0 ANSI Driver};Server=" & _
Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
rs.Open SQLStr, Cn, adOpenStatic
Range("A2").CopyFromRecordset rs
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub
this is multiple minutes faster

Problem with VBA script reading from MySql database

I am having some trouble with a vba script in Excel which should be
reading from a MySql database. The SQL query should only return one
record but actually returns an empty resultset. The generated statement works fine when run through phpMyAdmin.
Here is my code:
Function getClientId(emailAddress As String)
Dim rs As ADODB.Recordset
Dim sql As String
ConnectDB
Set rs = New ADODB.Recordset
sql = "SELECT client_id FROM clients WHERE email_address = '" & emailAddress & "' LIMIT 1"
Debug.Print sql
rs.Open sql, oConn
Debug.Print rs.RecordCount
If (rs.RecordCount = -1) Then
getClientId = Null
Else
getClientId = rs(0)
End If
rs.Close
End Function
EDIT: My database connect function.
Function ConnectDB()
On Error GoTo ErrHandler
Set oConn = New ADODB.Connection
oConn.Open "DRIVER={MySQL ODBC 5.1 Driver};" & _
"SERVER=localhost;" & _
"DATABASE=mydb;" & _
"USER=user;" & _
"PASSWORD=password;" & _
"Option=3"
'Debug.Print oConn
Exit Function
ErrHandler:
MsgBox Err.Description, vbCritical, Err.Source
End Function
The ConnectDB function is connecting ok as I am running other scripts
with it. If anyone can see what I am doing wrong then any help would
be appreciated.
Many thanks in advance.
Garry
MyODBC does not properly provide the RecordCount-Attribute.
Re: Problem with RecordCount with ASP & MySQL
rs.recordcount = -1 with myODBC
Re: ADO Connection RecordCount
So, if you really need the RecordCount, set CursorLocation Property to adUseClient.
If not, just iterate through the RecordSet like this:
Do While Not rs.EOF
'...do your magic
rs.MoveNext
Loop
Use " (double quote) instead of ' (single quote), because you are querying through the ODBC driver.
This could be problem of driver you have selected. My suggestion is (and I may be wrong) - if you are connecting via ODBC it could have different set of commands.