Terminating Query If Not Connection - sql

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.

Related

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

Error executing a saved Access query that depends on parameter values from a form

I'm trying to simply open a query and SELECT everything from it. The query requires FROM and TO dates. I have a frmA through which I pass the parameters to the query. I open the frmA and put in 2 dates. Funny thing is, when I do docmd.openQuery "qryInsurance" it opens it wihout a problem, however, when I try to Select * from qryInsurance, it tells me that it's expecting 2 parameters.
here is the code:
Public Function CountFollowup() As Boolean
On Error GoTo error_handler:
Dim rs1 As DAO.Recordset
Dim rs2 As DAO.Recordset
Dim strsql As String
Dim rcount As Integer
Set DB = CurrentDb
CountFollowup = False
DoCmd.OpenQuery "qryInsurance"
strsql = "SELECT * FROM [qryInsurance];"
'CurrentDb.Execute "Delete * FROM temp_InsData"
Set rs1 = CurrentDb.OpenRecordset(strsql, , dbOpenSnapshot) ' here is where it gives me an ERROR, expecting 2 parameters when it OPENS it fine before strsql
Set rs2 = CurrentDb.OpenRecordset("temp_InsData")
Debug.Print strsql
Exit Function
error_handler:
MsgBox Err.Number & " - " & Err.Description
End Function
It seems qryInsurance includes references to form controls, maybe like this ... Forms!frmA!From
Those references are resolved when you use DoCmd.OpenQuery, but not when you use the DAO.Database.OpenRecordset method. With OpenRecordset, they are interpreted as parameters for which you have not supplied values.
If you open the query's QueryDef and then feed each parameter Name to Eval(), it will give you the values of those form controls ... so you can then supply them as the values for the parameters.
That description may not be easy to follow, but the code is pretty easy.
Add these variable declarations before Set db = CurrentDb ...
Dim db As DAO.Database
Dim prm As DAO.Parameter
Dim qdf As DAO.QueryDef
Dim CountFollowup ' As what? Boolean?
Then later ...
Set db = CurrentDb
CountFollowup = False
'DoCmd.OpenQuery "qryInsurance"
'strsql = "SELECT * FROM [qryInsurance];"
'CurrentDb.Execute "Delete * FROM temp_InsData"
Set qdf = db.QueryDefs("qryInsurance")
For Each prm In qdf.Parameters
prm.Value = Eval(prm.Name)
Next
'Set rs1 = CurrentDb.OpenRecordset(strsql, , dbOpenSnapshot) ' here is where it gives me an ERROR, expecting 2 parameters when it OPENS it fine before strsql
Set rs1 = qdf.OpenRecordset(dbOpenSnapshot)
' and the rest ...

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

Invalid Operation Setting Result Set Object VBA

Hi Maybe someone can enlighten me here. Using VBA code and I want to include a check for zero record count from a query and it now fails at the code I added where it was fine before. Code below shows set up:
Sub MySub()
Dim db As DAO.Database
Set db = CurrentDb()
Dim qdf As DAO.QueryDef
Dim sqlQry As String
Dim rst As DAO.Recordset
sqlQry = "My Query String"
If DLookup("Name", "MSysObjects", "Name= 'QueryName1'") <> "" Then
Set qdf = CurrentDb.QueryDefs("QueryName1")
qdf.SQL = sqlQry
Else
Set qdf = CurrentDb.CreateQueryDef("QueryName1", sqlQry)
End If
Set rst = db.OpenRecordset(qdf.Name) << FAILS HERE
If rst.RecordCount <> 0 Then
DoCmd.OpenQuery (qdf.Name)
Else
MsgBox "no data returned"
Exit Sub
End If
Set qdf = Nothing
Set db = Nothing
End Sub
It fails on the line shown above with run "time error 3219 Invalid Operation". the only thing I changed is added an object reference for business objects for another part of the code, not this part. It ran fine before and only other change is start of a new sub below this code but running only this bit code (not the whole module) in debug mode it came up with the error.