Error while connecting to Access from Excel 2010 - ms-access

I wrote the following VBA code in Excel 2000 to create a connection to an Access 2000 with workgroup security in WindowsXP. Everything was working properly until we moved to Windows7 The database is still in Access2000.
It seems that the password value is eliminated from the ADODB connection string after opening a connection to the database. The first debug.print statement of the code below returns a string that contains the password and the user name but the second debug.print statement only shows the value of the User ID parameter. As a result when I try to create a recordset I get an error message that I do not have permission to the data.
Following the exact same procedure from Excel 2000 in Windows XP the ADODB connection string was not eliminating the password value and I was able to open a recordset.
Any suggestions?
Public Function sDbConnection() As String
Dim sString As String
Dim sConnection As String
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
conn.Provider = "Microsoft.Jet.OLEDB.4.0;"
' Provide path to the system Db
conn.Properties("Jet OLEDB:System database") = "S:\UTL\RscMgmt\SECURE.MDW"
' Username and password to the secured access database
conn.Properties("Password") = "MyPassword"
conn.Properties("User Id") = "MyUserID"
Debug.Print conn.ConnectionString
' Open a connection to the Access 2000 db and return the connection string
conn.Open "Data Source=" & "S:\UTL\RscMgmt\GasPortfolio 2000.mdb" & ";"
sConnection = conn.ConnectionString
Debug.Print sConnection
sDbConnection = sConnection
End Function

If you are on a 64 bit version of Win 7, the Microsoft.Jet.OLEDB.4.0 provider will not work, as it is only for 32-bit systems.
This website lists a few work-arounds you can implement.

Try it with "Microsoft.ACE.OLEDB.12.0" provider .

Related

How to Connect to an Access Database Using VBScript

I have an Access database for a client who wants to connect to and query the database using vbscript (so they can automate without actually opening the Access 2000 MDB). I can't figure out how to make the database connection.
I've tried several scripts, using both DAO and OLEDB. Below I've pasted the closest I've got, using an ODBC File DSN (I'm afraid using a System DSN would require extra work on the client's end, I'm trying to keep it simple).
Set objConnection = CreateObject("ADODB.Connection")
Set objRecordset = CreateObject("ADODB.Recordset")
'ERROR OCCURS HERE
objConnection.Open "FileDSN=D:\RLS.dsn;"
objRecordset.CursorLocation = adUseClient
objRecordset.Open "SELECT County FROM CountyTBL" , objConnection, adOpenStatic, adLockOptimistic
Here is the contents of RLS.dsn (I created this using Windows Control Panel so I am confident it's correct):
[ODBC]
DRIVER=Microsoft Access Driver (*.mdb)
UID=admin
UserCommitSync=Yes
Threads=3
SafeTransactions=0
PageTimeout=5
MaxScanRows=8
MaxBufferSize=2048
FIL=MS Access
DriverId=25
DefaultDir=D:\
DBQ=D:\RLS_be.mdb
The error message I got (and this was similar with the other 2 scripts I tried as well) was:
"Line 5, Char 4 Error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified. Source: Microsoft OLE DB Provider for ODBC Drivers"
You can simply use ADO to connect to the file without setting up a DSN. This will be simpler for your client.
For Access 2000, 2002-2003 MDB, use the following connection string:
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\RLS_be.mdb"
For Access 2007, 2010, 2013 ACCDB:
"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=D:\RLS_be.accdb"
The overall connection code:
' Build connection string
Dim sConnectionString
sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\RLS_be.mdb"
' Create connection object
Dim objConnection
Set objConnection = CreateObject("ADODB.Connection")
' Open Connection
objConnection.open sConnectionString
' Get recordset from SQL query
Dim objRecordset
Dim sQuery
sQuery = "SELECT County FROM CountyTBL"
Set objRecordset = CreateObject("ADODB.Recordset")
objRecordset.CursorLocation = adUseClient
objRecordset.Open sQuery, objConnection, adOpenStatic, adLockOptimistic
Here is another version using the connection string for a MS-Access 2016 database. The example connects to the 'clients.accdb' database and retrieves the value of the 'ClientID' field of the record where the 'ClientName' is equal to 'Joe Smith', then it loops through the records returned by the SQL statement.
Note that the extra quotations in the SQL statement are used in order to handle the scenario in which the name might contain a single quot ('), for example O'Connor.
Dim oConn, oRS
Dim ClientName : ClientName = "Joe Smith"
Set oConn = WSH.CreateObject("ADODB.Connection")
oConn.Open "Provider=Microsoft.ACE.OLEDB.16.0; Data Source=C:\test\clients.accdb"
Set oRS = oConn.Execute("Select ClientID From Clients Where ClientName=""" & ClientName & """")
Do While Not(oRS.EOF)
'Do something with the record.
oRS.MoveNext
Loop
oRS.Close
oConn.Close

What is the ConnectionString to connect MySQL db with VB.NET

I am working on to connect my App form VB.Net with MySQL table database with this code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim str As String = "data source=localhost;Initial Catalog=tabledb;user id=root;password=password1234"
Dim con As New SqlConnection(str)
con.Open()
Dim com As String = "Select * from springdata where rfid_tag='" & Rfid_tagTextBox.Text & "'"
Dim cm As New SqlCommand(com, con)
Dim rd As SqlDataReader = cm.ExecuteReader()
If rd.Read() = True Then
MessageBox.Show("Valid username and password")
Else
MessageBox.Show("Invalid username and password", caption:="login")
End If
End Sub
But when I run the app gave me this error:
Additional information: A network-related or instance-specific error
occurred while establishing a connection to SQL Server. The server
was not found or was not accessible. Verify that the instance name
is correct and that SQL Server is configured to allow remote
connections. (provider: Named Pipes Provider, error: 40 - Could not
open a connection to SQL Server)
What is the correct ConnectionString to use with MySQL 5.7.
The connection string below is an SQL Server connection string:
Dim str As String = "data source=localhost;Initial Catalog=tabledb;user id=root;password=password1234"
According to MySQL Connector .NET connection string, you should provide server name, port number (if using different port), database name and credentials like this:
Dim str As String = "Server=localhost;Port=3306;Database=tabledb;Uid=root;Pwd=password1234"
Also you should use MySqlConnection, MySqlCommand & MySqlDataReader instances with parameters instead of value concatenation inside query string (ensure that reference to MySql.Data.dll added first):
Using con As New MySqlConnection(str)
con.Open()
Dim com As String = "Select * from springdata where rfid_tag=#tag"
Using cm As New MySqlCommand(com, con)
cm.Parameters.Add("#tag", MySqlDbType.VarChar).Value = Rfid_tagTextBox.Text
Dim rd As MySqlDataReader = cm.ExecuteReader()
' Check if any rows exist
If rd.HasRows = True Then
' do something
Else
' do something else
End If
End Using
End Using

How to link tables with VBA code over ODBC

Actually I use a ODBC-Connection to connect Ms Acces to tables of a PostgreSQL-DB. I connect them by using the External Data/Import ODBC-Link command. It works fine.
But how can I use VBA to link my tables?
When using VBA to link a table with ODBC, you can add and APP= argument to specify an application name that will generally show in the properties of the connection on your database server.
For example, here is a sample ODBC Connection string for a linked table:
ODBC;Driver={SQL Server};Server=MyServer\SQLExpress;Database=MyDatabase;APP=My App Title;Trusted_Connection=Yes;
My App Title is the string that will be your Application Name for that connection.
Update 1 In response to further comment by the OP:
Here is sample code to link a table via ODBC in VBA. To facilitate this, you also should always delete the ODBC linked table each time before re-linking it to make sure that your options are respected, and that Microsoft Access updates the schema for the linked table. This example shows a connection string for a SQL Server database, so all you would need to change is the connection string for your PostgreSQL-DB. The remaining VBA code would be the same.
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim strConn As String
Dim ODBCTableName as String
Dim AccessTableName as String
Set db = CurrentDb()
ODBCTableName = "dbo.YourTable"
AccessTableName = "YourTable"
strConn = "ODBC;Driver={SQL Server};Server=YOURSERVER\SQLINSTANCE;Database=MYDATABASE;Trusted_Connection=No;UID=MyUserName;PWD=MyPassword"
db.TableDefs.Refresh
For Each tdf In db.TableDefs
If tdf.Name = AccessTableName Then
db.TableDefs.Delete tdf.Name
Exit For
End If
Next tdf
Set tdf = db.CreateTableDef(AccessTableName)
'===============================
'If your connection string includes a password
'and you want the password to be saved, include the following 3 lines of code
'to specify the dbAttachSavePWD attribute of the TableDef being created
'If you don't want to save the password, you would omit these 3 lines of code
'===============================
If InStr(strConn, "PWD=") Then
tdf.Attributes = dbAttachSavePWD
End If
tdf.SourceTableName = ODBCTableName
tdf.Connect = strConn
db.TableDefs.Append tdf
For some reason this code gives Run time error 3170 - Could not find installable ISAM. However, when you add ODBC; at the beginning of the connection string, then it works. So the connection string should look something like:
strConn = "ODBC;DRIVER={MySQL ODBC 5.2 Unicode Driver};" _
& "SERVER=servername;" _
& "DATABASE=databasename;" _
& "UID=username;PWD=password; OPTION=3"

VB.NET application with MySQL DSN connection for Crystal Reports asks for Logon info

I have an application written in VB.NET.
It was written for a client some time ago on 32 bit architecture.
The database is MySQL 5.5.
The reports were inbuilt Crystal reports and the database connectivity was ODBC 32bit MySQL connector through a DSN.
Now the client has upgraded all the clients to windows 10(64bit).
The desktop application works well with the same old 32bit connector, but when any report is run, it asks for a logon screen. Unfortunately, passing the login credentials at run-time doesn't work.
The code is as attached. I have browsed through all the answers, but the codes don't work. Is there something I am missing? Can anyone help?
I know the issue is an old one, but it is a running application for some years and we don't really need to rewrite.
Code: (Called on a button link)
Public Sub PrintAmcRemainderForIndus(ByVal componentId As Integer, ByVal AddressId As Integer)
'Dim cryRpt As New ReportDocument
Dim rPath As String = ""
Dim objForm As New frmViewReport
rPath = Application.StartupPath & "\Reports\rptAMCReminderForIndus.rpt"'
MessageBox.Show(rPath.Length & vbCrLf & rPath)
Dim crtableLogoninfos As New TableLogOnInfos()
Dim crtableLogoninfo As New TableLogOnInfo()
Dim crConnectionInfo As New ConnectionInfo()
Dim CrTables As Tables
Dim CrTable As Table
Dim TableCounter
Dim cryRpt As New rptAMCReminderForIndus()
'If you are using ODBC, this should be the DSN name NOT the physical server name. If
'you are NOT using ODBC, this should be the
'physical server name
With crConnectionInfo
.ServerName = "Indus"
'If you are connecting to Oracle there is no
'DatabaseName. Use an empty string.
'For example, .DatabaseName = ""
.DatabaseName = "indus"
.UserID = "root"
.Password = "simsoft"
End With
'This code works for both user tables and stored
'procedures. Set the CrTables to the Tables collection
'of the report
CrTables = cryRpt.Database.Tables
For Each CrTable In CrTables
crtableLogoninfo = CrTable.LogOnInfo
crtableLogoninfo.ConnectionInfo = crConnectionInfo
CrTable.ApplyLogOnInfo(crtableLogoninfo)
Next
Try
'cryRpt.Load(rPath)
Dim crParameterFieldDefinitions As ParameterFieldDefinitions
Dim crParameterFieldDefinition As ParameterFieldDefinition
Dim crParameterValues As New ParameterValues
Dim crParameterDiscreteValue As New ParameterDiscreteValue
crParameterValues.Clear()
crParameterDiscreteValue.Value = componentId
crParameterFieldDefinitions = cryRpt.DataDefinition.ParameterFields
crParameterFieldDefinition = crParameterFieldDefinitions.Item("piCustomerId")
crParameterValues = crParameterFieldDefinition.CurrentValues
crParameterValues.Add(crParameterDiscreteValue)
crParameterFieldDefinition.ApplyCurrentValues(crParameterValues)
crParameterDiscreteValue.Value = AddressId
crParameterFieldDefinitions = cryRpt.DataDefinition.ParameterFields
crParameterFieldDefinition = crParameterFieldDefinitions.Item("piAddressId")
crParameterValues = crParameterFieldDefinition.CurrentValues
crParameterValues.Add(crParameterDiscreteValue)
crParameterFieldDefinition.ApplyCurrentValues(crParameterValues)
objForm.rptViewer.ReportSource = cryRpt
objForm.Show()
Catch ex As Exception
MessageBox.Show(ex.Message & vbCrLf & ex.InnerException.Message)
End Try
End Sub
I would say that there is something wrong here:
'If you are using ODBC, this should be the DSN name NOT the physical server name. If
'you are NOT using ODBC, this should be the
'physical server name
With crConnectionInfo
.ServerName = "Indus"
Are you sure you are providing the name of the ODBC, not the hostname?
Have a look here:
http://www.tek-tips.com/faqs.cfm?fid=4870
and here:
How to set database login infos (connection info) for crystal report vb.net?

data source name not found or no default driver specified in vba

I am trying to connect mysql database using vba script but unfortunately i am getting an error "data source name not found or no default driver specified "
This is the code
Sub connection()
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 op As Long
server_name = "127.0.0.1" '
database_name = "test" 'database name
user_id = "root" ' user ID
password = "" ' password
Set conn = New ADODB.connection
conn.Open "DRIVER={MySQL ODBC 5.3 Unicode Driver};" & _
"SERVER=server_name;" & _
"DATABASE=database_name;" & _
"USER=user_id;" & _
"PASSWORD=password;" & _
"option=3" 'getting error at this point
End Sub
Please help me with that
I have also tested connection odbc and it works fine.I have 5.3 odbc driver
thanks in advance
The error message means one of a few different things:
You are referencing the driver incorrectly in your connection string, check to make sure that the driver name you're using is correct.
You're trying to reference a 32-bit driver from 64-bit VB or vice versa, ensure the bitnesses match.
The driver is installed incorrectly, are you able to create a DSN or connect via a different application such as Excel?