How to Connect to an Access Database Using VBScript - ms-access

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

Related

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"

Classic ASP adding records to MySQL

I have had to move on of my old classic ASP projects to a new host, and I'm having problems connecting to their MySQL server.
I have attached below the script I used with the old host which now errors
Data source name not found and no default driver specified
After a bit of digging it seems I have to change the driver to {MySQL ODBC 5.3 Unicode Driver} but it still errors. It seems to point to the cursor/lock type but I have used all option with no success.
ODBC driver does not support the requested properties.
<%
Dim Conn
Dim Rs
Dim sql
Set Conn = Server.CreateObject("ADODB.Connection")
Set Rs = Server.CreateObject("ADODB.Recordset")
Conn.Open "DRIVER={MySQL ODBC 3.51 Driver}; SERVER=xxx; PORT=xxx; DATABASE=xxx; UID=xxx; PASSWORD=xxx; OPTION=3"
sql= "SELECT * FROM table;"
Rs.CursorType = 2
Rs.LockType = 3
Rs.Open sql, Conn
Rs.AddNew
Rs.Fields("database") = Request.Form("form")
Rs.Update
Rs.Close
Set Rs = Nothing
Set Conn = Nothing
%>
You don't need this to insert a record. Instead, use plain SQL which should be supported by all database drivers:
Dim oCommand
Const adInteger = 3
Const adDate = 7
Const adVarChar = 200
sql = "Insert Into table (database) Values (?)"
Set oCommand = Server.Createobject("ADODB.Command")
Set oCommand.ActiveConnection = Conn
oCommand.CommandText = sql
oCommand.Parameters.Append(oCommand.CreateParameter("database", adVarChar, , 512, Request.Form("form")) )
oCommand.Execute
This is indeed bit more to write, but should preserve all the benefits of the other way (e.g. SQL Injections attack protection) and not being dependant on specific drivers.

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

Updating the data in an ODBC datasource with that in local Access DB?

I have a remote ODBC data source 'A' whose values is to be updated according to the table 'B' in the local access database. How can I do the same ?. I tried using pass through queries, however I am not able to access both the remote and local source in ONE SINGLE query. How should I do the same?
How does link tables work? Can I link my local table to the ODBC database dynamically using VBA?
In your Access database simply create a Linked Table for your ODBC data source:
For detailed instructions, see
About importing and linking data and database objects
Once that is done, you can use the linked table and the local table(s) in the same query from within Access:
You can't create a link dynamically that I am aware, though you could refresh a link that already existed.
What sort of joining is required? If you're just updating a single or a few rows, you might do this: (I can only write this using ado (means adding a reference to microsoft.activex data objects)
dim ss as string 'tempstr, sqlstr whatever you want to call it
dim cn as object: set cn = createobject("adodb.connection")
cn.Connection = [connection string required for ODBC datasource]
cn.Open
dim rst as object: set rst = createobject("adodb.recordset")
rst.open "SELECT required_data_column_list FROM localTable [WHERE ...]" _
, currentproject.connection, adOpenStatic, adLockReadOnly
do while not rst.eof
ss = "UPDATE ODBC_TableName SET ColumnA = '" & rst.Fields(3) & "' [, ... ]
ss = ss & " WHERE ... "
cn.Execute ss
do while cn.State = adStateExecuting
loop
rst.movenext
loop
set rst = nothing 'these statements free up memory,
set cn = nothing 'given that these objects are unmanaged
Hope this helps

Error while connecting to Access from Excel 2010

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 .