ODBC--Call failed on RecordSet - database

Hellow i need your help i have a access database software, so i decided to migrate into sql server by sql migration assistant after that i tested my linked tabled to my access Graphical user, but fails some of code it seems doesn't applied in that are linked in sql server my code is
Dim Activity As Recordset
Set Activity = CurrentDb.OpenRecordset("UserActivity")
Activity.AddNew
Activity!ActivityType = "Login To Afya DB"
Activity!RefDocument = Me.Name
Activity!Description = "User Has Seen Home_Page"
Activity!UserName = Me.txtUserName.Value
Activity!ActionedOn = Format(Now(), "dd/mm/yyyy")
Activity.Update
I have tryed to add dbSeeChanges
Set Activity = CurrentDb.OpenRecordset("UserActivity", dbOpenDynaset, dbSeeChanges)
Activity.AddNew
Activity!ActivityType = "Login To Afya DB"
Activity!RefDocument = Me.Name
Activity!Description = "User Has Seen Home_Page"
Activity!UserName = Me.txtUserName.Value
Activity!ActionedOn = Format(Now(), "dd/mm/yyyy")
Activity.Update
But still give this Massage i get wen am starting excuting and When i debug the problem is
Activity.Update

Always pass true date values to a date/time field; Format returns text.
Also, list the error information if any. So:
Set Activity = CurrentDb.OpenRecordset("UserActivity", dbOpenDynaset, dbSeeChanges)
Activity.AddNew
Activity!ActivityType = "Login To Afya DB"
Activity!RefDocument = Me.Name
Activity!Description = "User Has Seen Home_Page"
Activity!UserName = Me.txtUserName.Value
Activity!ActionedOn = Date
Activity.Update
' Print ODBC error.
Debug.Print Errors(0)

Related

How do I connect to a new Datasource in Access 2016 VBA?

My department uses an application created using VBA and Access 2016. It originally pointed to an Access database on one of our servers. After migrating the data to a different server, I now need it pointing to the other SQL Server database on that different server. But I can't seem to make the connection.
I have dbowner permissions on the server in question.
The original code for connection string was as follows:
'Remove the filter, close the log on form, and open the Switchboard
rst.Filter = 0
DoCmd.Close acForm, "frmUserLogOn"
'Open the Main Switchboard
DoCmd.OpenForm "frmMain", acNormal
'Open the InactiveShutDown form in Hidden mode
DoCmd.OpenForm "frmInactiveShutDown", acNormal, , , , acHidden
...
Set conn = CurrentProject.Connection
...
rstLog.Open "tblUserLog", conn, adOpenKeyset, adLockOptimistic
rstLog.AddNew
rstLog!UserID = rst!UserID
rstLog!TimeIn = Now()
rstLog.Update
My new code is as follows:
'DoCmd.OpenForm "frmInactiveShutDown", acNormal, , , , acHidden
'Commented out the above statement
...
'Set conn = CurrentProject.Connection
'==================================================================
'Start of Added Code for SQL Migration
Set conn = New ADODB.Connection
With conn
.ConnectionString = "Provider=SQLNCLI11;Data Source=(My Server Name);Initial Catalog=(My Database Name);User ID=(Username);Password=(Password)"
.Open
If .State = adStateClosed Then
MsgBox "Connection unsuccessful. Could not open connection.", vbInformation, "Error:"
End If
End With
Set rst = New ADODB.Recordset
With rst
.ActiveConnection = conn
.CursorLocation = adUseClient
.CursorType = adOpenStatic
.LockType = adLockOptimistic
.Open "tbl_Users"
End With
'End of Added Code for SQL Migration - See Section 2 for rest of code.
'==================================================================
...
'Section 2 of Code
'==================================================================
'Start of added code for SQL Migration
rstLog.Open "tblUserLog", conn, adOpenStatic, adLockOptimistic
rstLog.AddNew
rstLog!UserID = rst!UserID
rstLog!TimeIn = DateTime.Now()
rstLog.Update
MsgBox "Success! Connection was made successfully.", vbInformation
'End of added code for SQL Migration
'===================================================================
My form has a drop down to select list of users form a table. I added a test user in that table but that test user doesn't show up in the drop down list. Hence, I think the connection is not being made.
Do I have to enter the names for Data Source, Initial Catalog, User ID and Password in quotes? So UserID='Admin'; Password='Test'?
Anyone know what I'm doing wrong?
Basically, you have a version confusion of same named table between local Access frontend database and backend SQL Server database. Currently, your code updates the tblUserLog on the SQL Server backend side and is not the same tblUserLog on the Access frontend side which likely is the one bound to your form. Hence, why you cannot see any update as the server table is never shown.
Simply do one of two things:
Use SQL Server Version: Delete or archive the Access' version and add tblUserLog as an ODBC linked table. Be sure to remove the dbo_ or other schema prefix and keep same name tblUserLog. And since table names do not change, everything such as forms and VBA code should not need to change.
Use Access Version: Keep the local Access table, tblUserLog, and update this one in VBA which requires adding another connection object and running a recordset update on that connection. See below with prefixes of server_ and local_ on ADO objects:
' OPEN SERVER CONNECTION AND SERVER TABLE RECORDSET
Set server_conn = New ADODB.Connection
With server_conn
.ConnectionString = "Provider=SQLNCLI11;Data Source=(My Server Name);Initial Catalog=(My Database Name);User ID=(Username);Password=(Password)"
.Open
If .State = adStateClosed Then
MsgBox "Connection unsuccessful. Could not open connection.", vbInformation, "Error:"
End If
End With
Set server_rst = New ADODB.Recordset
With server_rst
.ActiveConnection = conn
.CursorLocation = adUseClient
.CursorType = adOpenStatic
.LockType = adLockOptimistic
.Open "tbl_Users"
End With
' OPEN LOCAL CONNECTION AND UPDATE LOCAL TABLE RECORDSET
Set local_conn = CurrentProject.Connection
Set local_rstLog = New ADODB.Recordset
local_rstLog.Open "tblUserLog", local_conn, adOpenStatic, adLockOptimistic
local_rstLog.AddNew
local_rstLog!UserID = server_rst!UserID ' NOTICE SERVER DATA USED HERE
local_rstLog!TimeIn = DateTime.Now()
local_rstLog.Update
...
' RELEASE RESOURCES
Set server_rst = Nothing: Set local_rstLog = Nothing
Set server_conn = Nothing: Set local_conn = Nothing

MS Access - SQL Server Login Prompt won't go away

So I have this application and I moved all local tables to SQL Server using upsizing, now they are currently linked tables. I'm able to access tables and forms related to tables can be accessed with no problems. But when I programmatically fetch a record, or perform a sql operation in VBA script, a SQL Server Login prompt pops up asking me to enter in the SQL Authentication login to access the database.
I followed this link here:
https://support.microsoft.com/en-us/kb/177594
Where this is my end code:
Dim db1 As Database
Dim db2 As Database
Dim rs As Recordset
Dim strConnect As String
Set db1 = OpenDatabase("C:\Workspace\ms1.mdb")
strConnect = UCase(db1.TableDefs("dbo_TableA").Connect) & ";UID=User1;PWD=Password1"
Set db2 = OpenDatabase("", False, False, strConnect)
db2.Close
Set db2 = Nothing
Set rs = db1.OpenRecordset("dbo_TableA")
rs.Close
db1.Close
Set rs = Nothing
Set db1 = Nothing
DoCmd.RunCommand acCmdSaveRecord
'Sql Server login prompt pops up after running the below code;'
If DCount("*", "TableA", "[ColA] = [forms]![FRM_LOGS]![USER]") = 0 Then
MsgBox "User ID not found - contact HelpDesk", vbCritical
DoCmd.Quit
Exit Sub
End If
The DCount is triggering the SQL Server Login Prompt. I need this prompt to go away. If I open up a form, query, report, anything where the access object is bound to the data, I get no message. It ONLY happens in VBA when I'm trying to access the data object.
Edit! I did find the culprit. I deleted the linked table to the TableA in sql server, and I relinked it again, and clicked the Save password checkbox. I did this before, and it didn't work. Did it again, and it fixed everything. Not sure why this didn't work the first time. I marked the below as an answer because that did solve the problem given the circumstances.
Not sure what you're doing here with two database connections and using DCOUNT on an internal table?
It looks like your database connection has linked tables that have stored passwords
Why not just use your recordset that works to check for a valid user?
Set db1 = OpenDatabase("C:\Workspace\ms1.mdb")
Set rs = db1.OpenRecordset("SELECT [ColA] FROM [dbo_TableA] WHERE [ColA] = """ & [forms]![FRM_LOGS]![USER] & """")
if rs.EOF Then
MsgBox "User ID not found - contact HelpDesk", vbCritical
DoCmd.Quit
Exit Sub
End If
rs.Close
db1.Close
Set rs = Nothing
Set db1 = Nothing

Microsoft Access Checkbox with SQL Backend Does Not Update

I've been researching it and have found many similar cases... but none exactly the same. I've tried a lot of different resolutions in the previous cases mentioned and none of them fixed this one.
I just recently did a SQL Server Migration and am now troubleshooting the issues that have sprung up with the new SQL back end. This is the last one that I can not figure out:
I have a split form with a check box control, bound to a SQL Server View through a DSN-Less connection. Before the migration the Bound Access Query could not be updated... so I programatically updated the forms checkboxes through VBA using two different methods:
Was a check all/ check none checkbox which when clicked checked or unchecked all of the checkboxes in the datasheet.
Gave the ability for the user to check or uncheck each individual checkbox by using the checkboxes Mouse_Down Event.
Here is the code for each of the two methods:
' Check All/ Check None
Dim rsSelect As DAO.Recordset
Dim rsUpdate As DAO.Recordset
Dim SQL As String
Dim CurrDb As Database
Dim currFilter As String
On Error GoTo chkSelect_Click_Error
' Capture current filter
If Me.FilterOn Then currFilter = Me.Filter
Set rsSelect = Me.RecordsetClone
Set CurrDb = CurrentDb
rsSelect.MoveFirst
Do While Not rsSelect.EOF
SQL = "SELECT * FROM tblTimesheet WHERE [TimesheetID] = " & rsSelect("TimesheetID")
Set rsUpdate = CurrDb.OpenRecordset(SQL, dbOpenDynaset, dbSeeChanges)
If Not rsUpdate.EOF Then
If Me.chkSelect Then
With rsUpdate
.Edit
rsUpdate("TimesheetSelect") = True
.Update
End With
Else
With rsUpdate
.Edit
rsUpdate("TimesheetSelect") = False
.Update
End With
End If
End If
rsSelect.MoveNext
Loop
rsUpdate.Close
rsSelect.Close
Me.Requery
If currFilter > "" Then
Me.Filter = currFilter
Me.FilterOn = True
End If
If Me.chkSelect Then
Me.lblSelect.Caption = "Select None"
Else
Me.lblSelect.Caption = "Select All"
End If
On Error GoTo 0
Exit Sub
chkSelect_Click_Error:
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure chkSelect_Click of VBA Document Form_frmTimesheetSummary"
And Secondly:
' Check/ Uncheck Individual Checkbox
Dim rsUpdate As DAO.Recordset
Dim SQL As String
Dim CurrDb As Database
Dim currFilter As String
' Capture current filter
If Me.FilterOn Then currFilter = Me.Filter
Set CurrDb = CurrentDb
SQL = "SELECT * FROM tblTimesheet WHERE [TimesheetID] = " & Me.TimesheetID
Set rsUpdate = CurrDb.OpenRecordset(SQL, dbOpenDynaset, dbSeeChanges)
If Not rsUpdate.EOF Then
If Me.TimesheetSelect Then
With rsUpdate
.Edit
rsUpdate("TimesheetSelect") = False
.Update
End With
Else
With rsUpdate
.Edit
rsUpdate("TimesheetSelect") = True
.Update
End With
End If
End If
rsUpdate.Close
Me.Form.Requery
'Me.Repaint
Me.Refresh
If currFilter > "" Then
Me.Filter = currFilter
Me.FilterOn = True
End If
Both of these procedures worked with an Access back end... but the "Check Individual" procedure refuses to work now. When I check a checkbox it does update the SQL Backend... but the control itself refuses to update the new status... I of course have tried Requery, but also Repaint and Refresh and it refuses to update unless I completely close the form and reopen it again.
The real kicker in all this is that the Check All method still works! I've spent hours on this and am hoping to get some fresh eyes on it because it should be working if the backend is updating!!
ADDITIONAL NOTES ADDED LATER: In response to some of the great reasoning below I feel I should include this additional notes:
I am using SQL Server 2012 and the SQL Server Native Client 11.0 Driver for my connection string.
I am using Microsoft Access 2010 32 bit
The SQL Server field is a bit I've removed all nulls and set allow nulls to 'no' with a default of 0
Some things come to mind:
1) You can replace the whole rsUpdate construction in the second procedure by this:
SQL = "UPDATE tblTimesheet SET TimesheetSelect = " & _
IIf(Me.TimesheetSelect, "0", "-1") & _
" WHERE TimesheetID = " & Me.TimesheetID
CurrDb.Execute SQL, dbSeeChanges
It depends on your TimesheetSelect datatype whether you should use "-1" or "1".
2) Me.Form.Requery should be Me.Requery.
3) If it still doesn't work, adding a TIMESTAMP column to tblTimesheet might help Access recognize that the record was changed. This is generally a good thing to have, but shouldn't be necessary.
Recommended reading: https://stackoverflow.com/a/2861581/3820271
tblTimesheet does have a primary key, doesn't it?
If Andre's suggestions don't solve it, instead of Me.Requery, try resetting the form's recordsource. Me.RecordSource = .
You don't say what version of SQL Server you are using or which ODBC driver. Make sure you are using the correct ODBC Driver for your version of SQL Server and not the default 'SQL Server' driver.
Thanks to all who posted... the answer that ended working for me in this case was ditching the split form... I had heard it suggested that split forms can be problematic at times so redesigned the form in a standard Parent/ Subform setup which completely resolved the issue.

Installable ISAM Error when trying to use DoCmd.TransferDatabase to link a table

I am trying to use DoCmd.TransferDatabase to link a SQL Server Express table to an Access 2013 table. I have no problems with other program code that accesses table data in SQL Server and Access.
The error message that I am getting is: "could not find installable ISAM".
I have had no success in running Microsoft's DoCmd.TransferDatabase sample programs or in finding an answer on the Web to the ISAM problem.
The code is as follows:
Set AccessConn = CreateObject("ADODB.Connection")
With AccessConn
.Provider = "Microsoft.Access.OLEDB.10.0"
'.Provider = "Microsoft.ACE.OLEDB.12.0"
.Properties("Data Provider").Value = "SQLOLEDB"
.Properties("Data Source").Value = TempVars!GlobalServerName
.Properties("User ID").Value = "sa"
.Properties("Password").Value = "xxxxxx"
.Properties("Initial Catalog").Value = TempVars!GlobalDatabaseName
.Open
End With
DoCmd.TransferDatabase acLink, "ODBC Database", _
"[ODBC;DSN={SQL Server Native Client 11.0};Server=XXXS1\SQLExpress;Database=ADatabaseName;Trusted_Connection=yes;]" _
& "DATABASE=D:\DatabaseDirectory\DatabaseTables.accdb", acTable, "Table1", "Table1;"
I had this problem, play with connection string, this worked for me.
"ODBC;Driver={ODBC Driver 17 for SQL Server};SERVER=MyServerName;DATABASE=MyDbName;Trusted_Connection=Yes;"
Private Sub PrintFormPB_Click()
'The purpose of this code is to be able to print Access Reports when the data are stored in
'a SQL Server database. One way to do this is to link all the SQL Tables to all the Access
'tables, but this has multiple disadvantages including the fact that the linker duplicates
'all of the SQL Table data in Access.
'This program only transfers Table data when it is required by Access Reports. The table
'data can then be deleted.
'There are several Report options. You can print the current Form page or all of the pages
'using a Report template. It is also possible to set a variety of printer options.
'This code links a SQL Server Table to an Access Table. The link command creates a new table
'that is named by appending a suffix the Table name. For example, Table allergies is linked
'as Allergies1. It is preferable to link to the original Table name, but the linker
'apparently cannot do this.
'This is part of an Open Source personal "MedicalRecords" program.
Dim strSQL As String
Dim database_path As String
Dim oRpt As Report
Dim AccessConn As New ADODB.Connection
Dim MsgBoxResponse As Integer
Dim ret As Integer
On Error GoTo ErrorHandler
'Setup the Access database connections
Set AccessConn = CreateObject("ADODB.Connection")
With AccessConn
.Provider = "Microsoft.Access.OLEDB.10.0"
'.Provider = "Microsoft.ACE.OLEDB.12.0"
.Properties("Data Source").Value = "D:\MedicalRecordsSQL\MedicalRecordTables.accdb"
.Open
End With
'The following links a SQL Server Table called Allergies to an Access Table called Allergies1.
'The Access table Allergies is then deleted and Allergies1 is renamed to Allergies.
'These are undesirable steps, but no alternative is known at this time.
'Note the formats of the SQL Server statements.
DoCmd.TransferDatabase acLink, "ODBC Database", _
"ODBC;Driver={SQL Server Native Client 11.0};SERVER=RERS1\SQLExpress;UID=sa;PWD=<your Password>;DATABASE=MedicalRecordsSQL;;Table=dbo.Allergies;" _
& "DATABASE=|D:\MedicalRecordsSQL\|MedicalRecordTables.accdb", acTable, "dbo.Allergies", "Allergies"
Set AccessConn = Nothing
DoCmd.DeleteObject acTable, "Allergies"
DoCmd.Rename "Allergies", acTable, "Allergies1"
'Setup Report
DoCmd.OpenReport "Allergies", acViewDesign, Null, Null, acHidden
Set oRpt = Reports(0)
oRpt.UseDefaultPrinter = True
'oRpt.Printer = Application.Printers("printer name")
'Set printer options
With oRpt.Printer
.PaperBin = acPRBNAuto
.PaperSize = acPRPSLetter
.Copies = 1
.PrintQuality = acPRPQMedium
.Orientation = acPRORLandscape
End With
'Print the report
DoCmd.Close acReport, "Allergies", acSaveYes
DoCmd.OpenReport "Allergies", acViewNormal, , "[ID] = " & Me.ID
Set oRpt = Nothing
Exit Sub
ErrorHandler:
MsgBoxReturn = MsgBox("Error Source: Allergies_Form" & vbCrLf & "Error Line: " & Erl & vbCrLf & "Error Number: " & Err.Number & vbCrLf & Err.Description, vbCritical, "")
End Sub

Requested operation requires an OLE DB Session object -- VB6 to SQL Server 2000

I'm attempting to get into a VB6 application that was written for a client about a decade back, but intermittently I keep getting this error. The application has a login required upon launch, and upon entering the login provided for me (I am 100% certain it is correct), the following error is given:
Run-time error '3709'
Requested operation requires an OLE DB Session
object, which is not supported by the current provider.
What's truly bizarre is that last night I was able to log in with absolutely no problems. However, I had this problem before about a week back, but I was out of town for several days and when I cam back I could log in again. Before that initial instance, I was able to log in fine. I noticed a similar question already posted, but the solution that was given did not work for me. Here's the code pertaining to establishing the database connection. Note, the Serv1, Use1, PW1 etc are just fillers for server names/usernames/passwords.
Public Function GetConnected()
' This function decides which server to connect and makes the connection
'Determines which connection string to use
If frmSplash.Text1 = "1" Or frmSplash.Text1 = "apc" Then 'server location
'determines if the logon contains '1' or 'apc'
'APC connection code
strSQLServerName = "(Serv1)"
strSQLDBUserName = "Use1"
strSQLDBPassword = "PW1"
strSQLPort = ""
ElseIf frmSplash.Text1 = "2" Then
'Laptop connection string
strSQLServerName = "(Serv1)"
strSQLDBUserName = "Use2"
strSQLDBPassword = "PW2"
strSQLPort = ""
Else
'Client connection code
strSQLServerName = "Serv2
strSQLDBUserName = "Use3"
strSQLDBPassword = "PW3"
strSQLPort = ""
End If 'server location
'If (m_DBConnection Is Nothing) Then
Set m_DBConnection = New ADODB.Connection
'End If
SessionLocation = frmSplash.LocationCombo.Text
'***************************************
'Connecs to database based on location
If frmSplash.LocationCombo.Text = "Loc1" Then
strSQLDBName = "ServLoc1"
ElseIf frmSplash.LocationCombo.Text = "Loc2" Then
strSQLDBName = "ServLoc2"
Else
strSQLDBName = "ServLoc3"
End If
'**************************
'Builds connection string
m_DBConnection.ConnectionString = "Provider=SQLOLEDB;" & _
"Data Source = '" & strSQLServerName & strSQLPort & "';" & _
"uid=" & strSQLDBUserName & ";" & _
"pwd=" & strSQLDBPassword & ";" & _
"Database=" & strSQLDBName & ";"
On Error GoTo errorhandler
m_DBConnection.Open
If (m_DBConnection Is Nothing) Then
MsgBox "Connection Failed"
End If
Exit Function
errorhandler:
MsgBox ("Problem with the Server")
'MsgBox "Connection State " & GetState(m_DBConnection.State)
End Function
Public Function ExecuteSQL(strSQL As String) As ADODB.Recordset
'Dim cmd As ADODB.Command
Set cmd = New ADODB.Command
**cmd.ActiveConnection = m_DBConnection** <-----(Error occurs here)
cmd.CommandType = adCmdText
cmd.CommandText = strSQL
Set ExecuteSQL = cmd.Execute
Exit Function
Variable definitions:
Public strSQLServerName 'Holds the name of the SQL Server
Public strSQLDBUserName 'Holds the user name (for SQL Server Authentication)
Public strSQLDBPassword 'Holds the password (for SQL Server Authentication)
Public strSQLDBName 'Holds name of a database on the server
Public strSQLPort 'Holds the Port Number
Public SessionUser As Integer ' To Track the type of User (3 Levels)
Public SessionLocation As String ' To Track the DB throughout the Session
Public m_DBConnection As ADODB.Connection
Public cmd As ADODB.Command
This is my first time working in VB6 and I'm a bit at a loss. I can't figure out why it works sometimes and not others. If anyone has any insights, they'd be very much appreciated.
Change your error handling to get a better idea of what is going on. Since you are setting your conncection (Set m_DBConnection = New ADODB.Connection) to a new object, your check (m_DBConnection Is Nothing) doesn't do much since the ojbect is certain to already exist.

Resources