ODBC Connection User and password persistent - vba

Sorry my English. I using Access 2016 32 bits and SQL Server 2019 I have the following routine
Dim tdf As dao.TableDef
Dim cadena As String
Dim db As dao.Database
Dim con As String
Set db = CurrentDb
For Each tdf In db.TableDefs
If InStr(tdf.Connect, "ODBC;") <> 0 Then
con = "ODBC;driver=SQL Server;server=miservidor;database=middbb;" _
& "UID=miusuario;PWD=micontraseña;"
tdf.Connect = con
tdf.RefreshLink
db.QueryDefs.Refresh
End If
Next tdf
Set tdf = Nothing
Set db = Nothing
after run it i can see all rows in linked tables but when exit the access app and open again if i try read rows i obtain the error "the connection is from a domain that is not trusted" and the username and password are not set in connect property of tables, If i run my routine again, i can open tables without any issue. I created a pass-through query and put the same connection string on it, it executes fine even when I exit and run access again. Any idea or solution ?. Thanks

Related

How Do I Keep Access Window Invisible When Queried from Word VBA

I can't keep Access Application Window from displaying when accessing an Access RecordSet from Word VBA.
I have VBA code in Word that creates an Access RecordSet from SQL, manipulates the RecordSet and then closes the Database. I have used Application.ScreenUpdating = False and set the Access Database object .Visible = False, but the Access Application Window keeps flashing on screen for an instant when the code runs.
Code fragment:
Dim acc as Access.Application
Dim db as Database
Dim rst as Recordset
Application.ScreenUpdating = False
Set acc = New Access.Application
With acc
.Visible = False
.OpenCurrentDatabase stAccPath
Set db = .CurrentDb
Set rst = db.OpenRecordset(stSQL)
Other code for manipulating recordset here.
.Quit
End With
set rst = Nothing
Set acc = Nothing
Application.ScreenUpdating = True
What I want to happen is to have Access running invisibly in the background when this code is executed, but in practice, the Access Application window appears on screen for a second before disappearing.
If the code does not need to interact with the user in the Access environment then it's better to not open the database at all. Instead, use an ADO connection retrieve the data directly from data storage, rather than opening the database in Access. This will not only avoid the problem with handling the (unwanted) Access application window, it will also be faster.
Here's some sample code for connecting to an Access database (both mdb and accdb connection strings are provided).
Sub AdoConnectAccess()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConn As String, sSQL As String
'sConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccessFile.accdb"
'sConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccessFile.mdb"
sSQL = "SELECT * From [Table Name]"
Set conn = New ADODB.Connection
conn.ConnectionString = sConn
conn.Open
Set rs = conn.Execute(sSQL)
rs.MoveFirst
Debug.Print rs.RecordCount, rs.Fields.Count
Do While Not rs.EOF
Debug.Print rs.Fields("Vorname").value
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing
End Sub

MS Access VBA Pass Through Query Connection String Error (ODBC)

I am currently trying to write a pass through query using VBA that connects to an oracle database. Using the answer provided from SQL Server Passthrough query as basis for a DAO recordset in Access as a starting poing, I have the following VBA code.
Option Compare Database
Sub Test_PassThroughQuery()
Dim qdf As DAO.QueryDef, rst As DAO.Recordset
Set qdf = CurrentDb.CreateQueryDef("")
qdf.Connect = "ODBC;DSN=database_name;UID=username;PWD=password;DBQ=ADPR;DBA=W;APA=T;EXC=F;FEN=T;QTO=T;FRC=10;FDL=10;LOB=T;RST=T;BTD=F;BNF=F;BAM=IfAllSuccessful;NUM=NLS;DPM=F;MTS=T;MDI=F;CSR=F;FWC=F;FBS=64000;TLO=O;MLD=0;ODA=F;"
qdf.SQL = "SELECT * FROM DATE_TABLE"
qdf.ReturnsRecords = True
Set rst = qdf.OpenRecordset
Debug.Print rst
rst.Close
Set rst = Nothing
Set qdf = Nothing
End Sub
However, this prompts an error Type mismatch on the Debug.Print rst.
For the connection string I am using the ODBC connection string from the Property tab.
EDIT Am I calling the Debug.print rst line incorrectly?
There are many ways to create pass-through queries. If you want to save a pass-through query in Access, you can set the first parameter of CreateQueryDef:
Sub Test_PassThroughQuery()
Dim qdf As DAO.QueryDef, rst As DAO.Recordset
Set qdf = CurrentDb.CreateQueryDef("MyPassthroughQuery")
qdf.Connect = "ODBC;DSN=database_name;UID=username;PWD=password;DBQ=ADPR;DBA=W;APA=T;EXC=F;FEN=T;QTO=T;FRC=10;FDL=10;LOB=T;RST=T;BTD=F;BNF=F;BAM=IfAllSuccessful;NUM=NLS;DPM=F;MTS=T;MDI=F;CSR=F;FWC=F;FBS=64000;TLO=O;MLD=0;ODA=F;"
qdf.SQL = "SELECT * FROM DATE_TABLE"
qdf.ReturnsRecords = True
DoCmd.OpenQuery "MyPassthroughQuery"
End Sub
This creates a saved query, and opens it.
You could also query an external data source in Access, which allows you to use the query designer, and use local tables and external data in a single query:
SELECT *
FROM [ODBC;DSN=database_name;UID=username;PWD=password;DBQ=ADPR;DBA=W;APA=T;EXC=F;FEN=T;QTO=T;FRC=10;FDL=10;LOB=T;RST=T;BTD=F;BNF=F;BAM=IfAllSuccessful;NUM=NLS;DPM=F;MTS=T;MDI=F;CSR=F;FWC=F;FBS=64000;TLO=O;MLD=0;ODA=F;].DATE_TABLE

Run-time error '3049' when qdf.Execute dbFailOnError in Access

I am trying to commit new data into the various databases and when I keep committing data after a while, it shows me this error:
The commit statment looks like this:
sql "INSERT INTO Bond Values("","HK0000122334","CNH",8447.5357732363,8447.5357732400,0.0000000037,109913,"01Jun15")".
The database reaches 2.09Gb as well. My code looks this:
Sub commit(dbName As String, tableName As String, commitString As String, reportDate As String)
Dim ws As DAO.Workspace
Dim db As DAO.Database
Dim sSQL As String
Dim qdf As QueryDef
sDb = dbName & ".accdb"
Set ws = DBEngine.Workspaces(0)
Set db = ws.OpenDatabase(sDb)
sqlStatementList = Split(commitString, ";")
For Each sqlStatement In sqlStatementList
sqlStatement = Replace(sqlStatement, ")" & vbLf, reportDate)
If InStr(tableName, "EIS") <> 0 Then
sqlStatement = Replace(sqlStatement, "EIS", tableName)
End If
sSQL = sqlStatement
Set qdf = db.CreateQueryDef("", sSQL)
qdf.Execute dbFailOnError
Next sqlStatement
End Sub
What I have tried so far:
1)
Set qdf = Nothing
Set db = Nothing
This did not help. Still the same issue.
2) Tried to delete that particular database and proceeded with committing to the rest of databases but still had the same issue.
Need some guidance on solving this.
The maximum size of an Access database is 2GB (Link is for 2010, but 2013 appears to be the same). So yes your insert will fail when the database gets that large. Your options are to break the data into another database file or switch to SQL Server or some other database type.

Execute a SQL Server stored procedure from MS Access

I use MS Access 2013 and SQL Server 2012. I have connected my SQL Server database to MS Access. I connect to SQL Server via SQL Server Authentication. I want to execute a stored procedure with a value entered into a textbox in one of my forms. I have been trying to do it for ages now but nothing that I found on this website works for me. Can anyone please help me and give me some tips as to how to write a basic VBA code to execute the procedure? Please help!!!
Probably the most straightforward way is to create a temporary pass-through query using a DAO.QueryDef object. If you have an existing linked table in Access then you can use its .Connect property (ODBC connection information). All you need to do is set the .SQL property of the QueryDef to call (EXEC) the stored procedure, like this:
Option Compare Database
Option Explicit
Private Sub Command2_Click()
Dim cdb As DAO.Database, qdf As DAO.QueryDef
Set cdb = CurrentDb
Set qdf = cdb.CreateQueryDef("")
' get .Connect property from existing ODBC linked table
qdf.Connect = cdb.TableDefs("dbo_myContacts").Connect
qdf.sql = "EXEC dbo.addContact N'" & Replace(Me.Text0.Value, "'", "''") & "'"
qdf.ReturnsRecords = False
qdf.Execute dbFailOnError
Set qdf = Nothing
Set cdb = Nothing
End Sub
So, for example, if the Text0 text box contains Thompson then the QueryDef will execute
EXEC dbo.addContact N'Thompson'
and if the text box contains O'Rourke then the QueryDef will execute
EXEC dbo.addContact N'O''Rourke'
After Trial and error this one worked for me
> Private Sub UpdateItems_Click()
> Dim cdb As DAO.Database, qdf As DAO.QueryDef
> Set cdb = CurrentDb
> Set qdf = cdb.CreateQueryDef("")
> ' get .Connect property from existing ODBC linked table
> qdf.Connect = cdb.TableDefs("dbo_AccesLinkedTable").Connect
> qdf.SQL = "EXEC dbo.YourStoreProcedure"
> qdf.ReturnsRecords = False
> qdf.Execute dbFailOnError
> Set qdf = Nothing
> Set cdb = Nothing
>
> MsgBox "Records Updated!"
>
> End Sub

Terminating Query If Not Connection

I have a code that uploads data to a SQL server database, I am trying to add in an IF line of code saying if there is a connection then to continue, but if there is not a connection then to END. I am having a difficult time figuring out the wording and placement though. The beginning of the code that connects is:
Public Function Update()
Dim cdb As DAO.Database, qdf As DAO.QueryDef
Dim rs As DAO.Recordset
Dim err As DAO.Error
Const ConnectionString = _
"ODBC;" & _
"Driver={SQL Server Native Client 10.0};" & _
"Server=SERV;" & _
"Database=DB;" & _
"UID=ID;" & _
"PWD=PWD;"
Set cdb = CurrentDb
Set qdf = cdb.CreateQueryDef("")
Set rs = CurrentDb.OpenRecordset("CDData", dbOpenTable)
qdf.Connect = ConnectionString
Do While Not rs.EOF
While one can simple attempt to execute any query or command, the “time out” and delay to test for an active connection can result in a VERY LONG delay. As a result a wonderful trick exists that uses a DIFFERENT connection mechanism in Access and thus “reduces” the potential VERY long delay when attempting to use a saved query that is based on linked tables. (that "different" connection system occurs when you create a queryDef as opposed to a linked table or a query based on a linked table to sql server)
The follow code will return true or false if you have a working SQL connection:
Function TestLogin(strcon As String) As Boolean
On Error GoTo TestError
Dim dbs As DAO.Database
Dim qdf As DAO.QueryDef
Set dbs = CurrentDb()
Set qdf = dbs.CreateQueryDef("")
qdf.Connect = strcon
qdf.ReturnsRecords = False
'Any VALID SQL statement that runs on server will work below.
qdf.SQL = "SELECT 1 as test"
qdf.Execute
TestLogin = True
Exit Function
TestError:
TestLogin = False
Exit Function
End Function
So in code you now with your connection string code go:
If TestLogIn(strConn) = false then
msgbox "no connection or logon invalid"
exit sub
End If
' record processing code goes here for successful logon/connection.