Connecting to Mysql db in Excel - mysql

So, I have to write a piece of code at my internship to link some excel worksheets with a MySQL DB and keep them updated, so far I have this but it keeps giving me errors. Do you see any mistakes?
Thanks for reading.
The error I get is: runtime error -2147217900 automation error.
PS: I'm very new to VBA
Dim server_name As String
Dim database_name As String
Dim user As String
Dim Password As String
Dim rs As adodb.Recordset
Dim naam As String
Dim oConn As adodb.Connection
Public Sub getSerieNummer()
Dim result As String
Dim b As Long
Dim strSQL As String
naam = Range("C1").Value
server_name = "servername"
database_name = "dbname"
user_id = "idname"
Password = "password"
Set oConn = New adodb.Connection
oConn.Open "SERVER=" & server_name _
& ";PORT=3306" _
& ";DATABASE=" & database_name _
& ";UID=" & user_id _
& ";PWD=" & Password & _
";DSN=name_in_odbc;"
strSQL = "SELECT [serial_number] FROM view_aix WHERE [name] ='" & naam & "';"
Set rs = oConn.Execute(strSQL)
b = 0
With rs
Do Until .EOF
b = b + 1
result = !serial_number
rs.MoveNext
Loop
End With
oConn.Close
rs.Close
Set rs.ActiveConnection = Nothing
Set oConn = Nothing
Range("C2").Value = result
End Sub

MySQL do not support "[" instead use " ` ".
Maybe is your connection string the problem.
ODBC Connection Style
Driver={mySQL};Server=localhost;Option=16834;Database=myDataBase;
OLEDB Connection Style
Provider=MySQLProv;Data Source=mydb;User Id=myUsername;Password=myPassword;

Related

Type mismatch, opening a RecordSet

Getting this error all time:
Run-time error '13': Type mismatch.
On this line
rs.Open , sqlstr, conn
I tried everything and can't solve the problem. I'm trying to update one row in MySQL database.
Private Sub CommandButton3_Click()
Dim conn As New ADODB.Connection
Dim server_name As String
Dim database_name As String
Dim user_id As String
Dim password As String
Dim i As Long
Dim sqlstr As String
Dim table1 As String, table2 As String
Dim field1 As String, field2 As String
Dim rs As ADODB.Recordset
Dim vtype As Variant
server_name = "99.99.99.99"
database_name = "name"
user_id = "user"
password = "pass"
Set conn = New ADODB.Connection
conn.Open "DRIVER={MySQL ODBC 3.51 Driver}" _
& ";SERVER=" & server_name _
& ";DATABASE=" & database_name _
& ";UID=" & user_id _
& ";PWD=" & password _
& ";OPTION=16427"
Set rs = New ADODB.Recordset
sqlstr = "SET SQL_SAFE_UPDATES = 0; UPDATE table SET poslano = 'Poslano' WHERE poslano = 'Neposlano';"
rs.Open , sqlstr, conn
With Worksheets("List6").Cells("A1")
.ClearContents
.CopyFromRecordset rs
End With
skipextract:
On Error Resume Next
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing
On Error GoTo 0
End Sub
The comma after rs.Open makes VBA "think" that the Source is omitted:
Thus, it gives Type mismatch error. Try to write it like this:
rs.Open sqlstr, conn

How to connect mysql database using vba?

Option Explicit
Sub excelmysql()
' Connection variables
Dim conn As New ADODB.Connection
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
' Table action variables
Dim i As Long ' counter
Dim strSQL As String ' SQL to perform various actions
Dim table1 As String
Dim field1 As String, field2 As String
Dim rs As ADODB.Recordset
Dim vtype As Variant
Server_Name = "localhost" ' Enter your server name here - if running from a local computer use 127.0.0.1
Database_Name = "PRMJIRA" ' Enter your database name here
User_ID = "root" ' enter your user ID here
Password = "Pradee#1234" ' Enter your password here
Set conn = New ADODB.Connection
conn.Open "DRIVER={MySQL ODBC 8.0 Unicode Driver}" _
& ";SERVER=" & Server_Name _
& ";DATABASE=" & Database_Name _
& ";UID=" & User_ID _
& ";PWD=" & Password _
& ";OPTION=16427"
'conn.Open
vtype = Array("varchar(255)", "Text", "LongText", "Int(10)", "Float", "Double", "Date", "Time") ' array of commonly used MySQL variable types
table1 = "P" & Range("H1").Value
field1 = "field1text"
field2 = "field2text"
strSQL = "CREATE TABLE `" & table1 & "` (`" _
& field1 & "` " & vtype(0) & ",`" _
& field2 & "` " & vtype(4) _
& ")"
conn.Execute strSQL
On Error Resume Next
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing
On Error GoTo 0
End Sub

Deleting mysql table entries using a macro

I am writing a macro by which I want to delete few names in column A of sheet 2 from the server table called login.
Database name is "my_db" and table name is login. I calling connection to connect to the server databse. Following is the complete code :-
Dim cnt As ADODB.Connection
Dim rst As ADODB.Recordset
Dim Sql As String
Sub Button1_Click()
Dim Ws As Worksheet
Dim Var As String
Dim i As Integer
i = 1
Set Ws = Worksheets("Sheet2")
Var = "login"
Sql = "name"
Call Connection
Do
Sql = " Delete From " & " " & Var & "" & " Where name" = "Ws.Cells(i, 1)"
Call Connection
i = i + 1
Loop Until Ws.Cells(i, 1) = ""
MsgBox "All entries deleted from login table"
End Sub
Dim strUserName As String
Dim strPassword As String
Dim ConnectString As String
Set cnt = New ADODB.Connection
strServerName = "localhost"
strDatabaseName = "my_db"
strUserName = "root"
strPassword = "root1"
ConnectString = "DRIVER={MySQL ODBC 5.1 Driver};" & _
"SERVER=" & strServerName & _
";DATABASE=" & strDatabaseName & ";" & _
"USER=" & strUserName & _
";PASSWORD=" & strPassword & _
";OPTION=3;"
With cnt
.CursorLocation = adUseClient
.Open ConnectString
.CommandTimeout = 0
Set rst = .Execute(Sql)
End With
'rst.Close
'cnt.Close
Set rst = Nothing
Set cnt = Nothing
End Sub
But the entries are not getting deleted. There is an error in SQL syntax, can anyone help me with the sql syntax ?
Sql = "delete From " & Var & " where name ='" & Ws.Cells(i, 1).Value & "'"
but it would be better to open the connection only once, run all the deletes, and then close the connection.
Also you don't need a recordset here (since you're not returning any records), so you can ignore the return value from cnt.Execute
Since you pasted the code only partially, I can only guess.
Do
Sql = " Delete From " & Var & " Where name" = "Ws.Cells(i, 1)"
Call Connection (Sql)
i = i + 1
Loop Until Ws.Cells(i, 1) = ""
Clean up your query. And more important pass it as a parameter to the connection.

Excel VBA MySQL "SELECT * FROM table" not full informaton

I have a really weird issue with my Excel VBA code selecting values from a MySQL database. I structured a simple database with following columns:
ID
Name
Surname
City
And lets assume having following entrys:
01; Pan; Peter; NYC
02; P; Peter; NYC
But now the issue, if I select * from my table it shows me only following output:
01; P; Pan; NYC
02; P; Pan; NYC
That means the I only see the minimal lenght of an entry .... what is going on there? I have really casual VBA code in different modules for that task:
Public variables:
Public cn As ADODB.Connection
Public rs As ADODB.Recordset
Public strSql As String
Connection module:
Public Function connectDB()
Dim strServer_Name As String
Dim strDB_Name As String
Dim strUser_ID As String
Dim strPassword As String
With Sheet2
strServer_Name = .Range("B2").Value
strDB_Name = .Range("B3").Value
strUser_ID = .Range("B4").Value
strPassword = .Range("B5").Value
End With
Set cn = New ADODB.Connection
cn.Open "DRIVER={MySQL ODBC 5.3 Unicode Driver}" & _
";SERVER=" & strServer_Name & _
";DATABASE=" & strDB_Name & _
";UID=" & strUser_ID & _
";PWD=" & strPassword & ""
End Function
Sub module:
Sub request()
strSql = "SELECT * FROM test"
Call connectDB
Set rs = New ADODB.Recordset
rs.Open strSql, cn, adOpenDynamic
With Sheet1.Range("A1")
.ClearContents
.CopyFromRecordset rs
End With
Call disconnectDB
End Sub
Is this a VBA issue or are there any bugs in my MySQL?
Okay guys I've found a solution in this post: sql-query-doesnt-return-full-results-for-only-one-field
Solved it the same way the other guy did. In my code it looks like this:
Sub request()
Dim iCols As Integer
Dim iRows As Integer
strSql = "SELECT * FROM test"
Call connectDB
Set rs = New ADODB.Recordset
rs.Open strSql, cn, adOpenDynamic
iRows = 10
While Not rs.EOF
For iCols = 0 To rs.Fields.Count - 1
Tabelle1.Cells(iRows, iCols + 1).Value = rs.Fields(iCols).Value
Next
rs.MoveNext
iRows = iRows + 1
Wend
Call disconnectDB
End Sub
But thanks to everyone who tried to help me!

Search Functionality RunTime error 424 at Select

My requirement: To search for data in database, using VB forms and 3 text boxes.
1 TextBox, I will give Input (UserName)
1 TextBox for Location
1 TextBox for displaying output
My code is
Private Sub CommandButton3_Click()
Dim Cn As ADODB.Connection '* Connection String
Dim oCm As ADODB.Command '* Command Object
Dim sName As String
Dim rs As ADODB.Recordset
Dim uname As String
Set Cn = New ADODB.Connection
Cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=d:\test2.accdb;Persist Security Info=False"
Cn.ConnectionTimeout = 40
Cn.Open
Set oCm = New ADODB.Command
oCm.ActiveConnection = Cn
‘Record Set
Set rs = New ADODB.Recordset
‘Select Operation
rs.Open "SampleTable", Cn, adOpenKeyset, adLockPessimistic, adCmdTable
uname = rs("UserName")
rs.Open "Select * from SampleTable where uname = '" & text1.Text & "'", ActiveConnection, adOpenForwardOnly, adLockReadOnly, adCmdText
**'Display the Output in TextBox3**
TextBox3.Text = rs("UserName") + rs("Location")
rs.Close
Cn.Close
End Sub
I can understand the population of data is not happening so getting a RunTime error 424 at Select statement. How can I retrieve the data for the corresponding Input given?
You do not need to open the table; rs.Open "SampleTable" before searching it.
Not sure what this is for; uname = rs("UserName")
You should just run; rs.Open "Select * ... (Running the .Open on the same RS twice without closing the first is probably whats causing your error)
You should escape your input; replace$(text1.Text, "'", "''")
You should check for rs.EOF after the .open
Use & not + for concatenating strings
update
sub xxx
Dim Cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sName As String
Set Cn = New ADODB.Connection
Cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=d:\test2.accdb;Persist Security Info=False"
Cn.ConnectionTimeout = 40
Cn.Open
Set rs = New ADODB.Recordset
sName = replace$(text1.Text, "'", "''")
rs.Open "Select * from SampleTable where UserName = '" & sName & "'", Cn, adOpenForwardOnly, adLockReadOnly, adCmdText
if (rs.eof) then
msgbox "no match"
else
TextBox3.Text = rs("UserName") & " " & rs("Location")
rs.Close
end if
set rs = nothing
Cn.Close
set cn = nothing
end sub