Create a linked table in Access from Teradata without DSN? - ms-access

Connection to Teradata
'Requires reference to ADO and ADOX
Public adoCn As ADODB.Connection
Public adoCat As New ADOX.Catalog
Public adoTbl As New ADOX.Table
Function TD_Make_Linked_Table()
Dim varServer As String
Dim varDatabase As String
Dim varUser As String
Dim varPassword As String
varServer = "Test"
varDatabase = "Test_Test"
varUser = "Test_User"
varPassword = "Test_Password"
Set adoCn = New ADODB.Connection
'I have tried multiple connection strings
adoCn.ConnectionString = "PROVIDER=MSDASQL;DRIVER={Teradata};" & _
"DBCName=" & varServer & ";" & _
"DefaultDatabase=" & varDatabase & ";" & _
"UID=" & varUser & ";" & _
"PWD=" & varPassword & ";"
adoCn.Open
Set adoCat = New ADOX.Catalog
Set adoCat.ActiveConnection = adoCn
Set adoTbl = New ADOX.Table
adoTbl.ParentCatalog = adoCat
adoTbl.Name = "Test"
'I have tried multiple property combinations
'Causes error 3265 Item not found
'adoTbl.Properties("?") = adoCn
'adoTbl.Properties("Jet OLEDB:Link Datasource") = "Test"
'adoTbl.Properties("Jet OLEDB:Link Provider String") =
'adoTbl.Properties("Jet OLEDB:Remote Table Name") = "LinkDatabaseTable"
'adoTbl.Properties("Jet OLEDB:Create Link") = True
'Causes 3251 provider is not capable of performing operation
'adoCat.Tables.Append adoTbl
adoCn.Close
Set adoTbl = Nothing
Set adoCat = Nothing
Set adoCn = Nothing
End Function
I have validated the connection is working. I can query data by opening the connection and executing SQL.
I am unable to create a linked table programmatically in Access using visual basic for applications with the created connection.
Has anyone been able to successfully create a linked dsn-less table from Access to Teradata?

If you have a working ODBC connection string then you should be able to use DoCmd.TransferDatabase to create a linked table. I don't have a Teradata server handy, but this works for me with SQL Server:
Dim connStr As String
connStr = _
"DRIVER=ODBC Driver 11 for SQL Server;" & _
"SERVER=(local)\SQLEXPRESS;" & _
"DATABASE=myDb;" & _
"Trusted_Connection=yes"
DoCmd.TransferDatabase _
TransferType:=acLink, _
DatabaseType:="ODBC Database", _
DatabaseName:="ODBC;" & connStr, _
ObjectType:=acTable, _
Source:="dbo.projects", _
Destination:="dbo_projects"

I eventually found a connection string that works! :)
Function adoTera()
Dim oConn As ADODB.Connection
Dim rs As ADODB.Recordset
Set oConn = New ADODB.Connection
Set rs = New ADODB.Recordset
oConn.ConnectionString = "PROVIDER=MSDASQL;" & _
"DRIVER={Teradata};" & _
"DBCName=yourDBCName;" & _
"DefaultDatabase=yourDBName;" & _
"UID=yourUserName;" & _
"PWD=yourPassword;"
oConn.Open
rs.Open "SELECT * FROM yourTable", oConn
ThisWorkbook.Worksheets("Sheet1").Range("A:A").CopyFromRecordset rs
rs.Close
oConn.Close
Set rs = Nothing
Set con = Nothing
End Function

Related

Trying to extract data from MySQL to Excel using VBA

I am getting an error and I don't understand what is the problem. Here is my code
Sub test()
Dim rs As ADODB.Recordset
Dim sqlstr As String ' SQL to perform various actions
Dim oConn As ADODB.Connection
Set oConn = New ADODB.Connection
oConn.Open "DRIVER={MySQL ODBC 5.3 Unicode Driver};" & _
"SERVER=ETS-DEV-01;" & _
"DATABASE=reporting;" & _
"USER=guest_user;" & _
"PASSWORD=0X4ZT9kwsY%yGOp;" & _
"Option=3"
sqlstr = "select * from tveuptimes"
rs.Open sqlstr, oConn
End Sub
I am getting the error:
Run-time error '91'
Object variable or with block variable not set.
I don't understand what i am doing wrong.
The line Set oConn = New ADODB.Connection isn't necessary. Instead, when you dimension rs and oConn add the word New before the type, like this:
Sub test()
Dim rs As New ADODB.Recordset
Dim sqlstr As String
Dim oConn As New ADODB.Connection
oConn.Open "DRIVER={MySQL ODBC 5.3 Unicode Driver};" & _
"SERVER=ETS-DEV-01;" & _
"DATABASE=reporting;" & _
"USER=guest_user;" & _
"PASSWORD=0X4ZT9kwsY%yGOp;" & _
"Option=3"
sqlstr = "select * from tveuptimes"
rs.Open sqlstr, oConn
End Sub
Here's a good tutorial: http://analysistabs.com/excel-vba/ado-sql-macros-connecting-database/

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.

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

how to create custom function in excel to grab mysql data?

We need to create a custom formula for users to pull data from our mysql database. After the user is authenticated, they would type in a formula in excel (something like '=retrievemybirthday("Frank Dodge")'. How do we go about doing that? We're not new to programming, just new to programming w/ Excel. Are there any tutorials on this? We've looked but can find anything.
thanks!
1) you need an ODBC driver configured for your MySQL db.
2) figure out the SQL code you need for this function, something like
select birthdate
from YourTable
Where membername=?
You will use this code in your function
3) In your function, you will need the correct Connection String. Check a site like http://www.connectionstrings.com/
4) Here's an example of a function, using ActiveX Data Objects (you need a reference set in Tools > References in the VB Editor)
Function GetNomen(sPN As String) As String
'SkipVought/2006 Mar 7
'--------------------------------------------------
' Access: DWPROD.FRH_MRP.READ
'--------------------------------------------------
':this function returns nomenclature for a given part number
'--------------------------------------------------
'2011-9-26 Converted to Parameter Query
'--------------------------------------------------
Dim sConn As String, sSQL As String, sServer As String
Dim rst As ADODB.Recordset, cnn As ADODB.Connection, cmd As ADODB.Command
Set rst = New ADODB.Recordset
Set cnn = New ADODB.Connection
Set cmd = New ADODB.Command
sServer = "dwprod"
cnn.Open "Driver={Microsoft ODBC for Oracle};" & _
"Server=" & sServer & ";" & _
"Uid=/;" & _
"Pwd="
sSQL = "SELECT PM.Nomen_201 "
sSQL = sSQL & "FROM FRH_MRP.PSK02101 PM "
sSQL = sSQL & "WHERE PM.PARTNO_201 =?"
Debug.Print sSQL
With cmd
.CommandText = sSQL
.CommandType = adCmdText
.Prepared = True
.Parameters.Append .CreateParameter( _
Name:="PARTNO_201", _
Type:=adChar, _
Direction:=adParamInput, _
Size:=16, _
Value:=sPN)
.ActiveConnection = cnn
Set rst = .Execute
End With
rst.MoveFirst
If Err.Number = 0 Then
GetNomen = rst("NOMEN_201")
Else
GetNomen = ""
End If
rst.Close
cnn.Close
Set cmd = Nothing
Set rst = Nothing
Set cnn = Nothing
End Function
You can run this function on the sheet as requested.

Error in VBA: Lost Connection to MySQL Server at 'reading authorization packet',system error 2

This is the error which I get after my macro executes for about 10 mins. The macro is basically performing the task to update the MySQL database every five seconds.
What could be wrong?
My macro is as below:
Public RunWhen As Double
Public Const cRunIntervalSeconds = 10 ' five seconds
Public Const cRunWhat = "UpdateMarketData" ' the name of the procedure to run
Sub UpdateMarketData()
Dim Cn As ADODB.Connection
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
rad = 0
TextStrang = TextStrang & "'"
field2 = "cid"
field1 = "bid"
table1 = "MMbanner"
For rowCursor = 3 To 4
SQLStr = "UPDATE tbl_MarketData SET Mid = '" & Cells(rowCursor, 2) & "',Bid = '" & Cells(rowCursor, 5) & "',Offer = '" & Cells(rowCursor, 6) & "',DateEntered = '" & Format(DateTime.Now(), "yyyy-MM-dd hh:mm:ss") & "' WHERE IndexCode = '" & Cells(rowCursor, 1) & "'"
Debug.Print SQLStr
Set Cn = New ADODB.Connection
Cn.Open "DRIVER={MySQL ODBC 3.51 Driver};SERVER=<Servername>; PORT=Portno; DATABASE=Databasename; USER=Username; PASSWORD=Password; OPTION=0;"
Cn.Execute SQLStr
rad = rad + 1
Next
Set rs = Nothing
Cn.Close
Set Cn = Nothing
Call StartTimer
End Sub
Sub StartTimer()
RunWhen = Now + TimeSerial(0, 0, cRunIntervalSeconds)
Application.OnTime EarliestTime:=RunWhen, Procedure:=cRunWhat, _
Schedule:=True
End Sub
Sub StopTimer()
On Error Resume Next
Application.OnTime EarliestTime:=RunWhen, Procedure:=cRunWhat, _
Schedule:=False
End Sub
Your for loop creates two separate connections via Set Cn = New ADODB.Connection etc but Cn.Close is only called once after the for loop. Therefore, the first connection created isn't explicitly closed and may still be considered active by the server. Eventually you'll run out of available connections and things will grind to a halt.
Not sure if this is the cause of your problem but it's definitely worth fixing. I would create and open the connection prior to the for loop but keep the Cn.Execute part within the body of the loop