Stoping Macro if Connection is Lost - sql

I have a series of codes that run when designated, the first is a connection check. If it is successful then it allows the code to continue, if not it stops it altogether. I am worried however about what happens when the connection is lost after this process. There is data on a local table that is uploaded to our SQL server during this process, if the connection terminates mid download it looks like sometimes the data is still transferred but not if it happens right away.
The second part of the code, deletes all the local tables contents which contain employee information, then downloads the new data so if there were any updates the most recent information is provided.
I am trying to figure out if there is a method or code that can be implemented to tell the query to stop running as soon as connection is lost, or if there is a way to undo it if it happens.
Or would it be a good idea to combine the connection code with the upload and delete codes so it runs every time before it initiates a process?
The connection code that runs at the beginning is:
Public Function StartUp()
Dim cnn As ADODB.Connection
Dim localrst As New ADODB.Recordset
Dim remoterst As New ADODB.Recordset
On Error Resume Next
Set cnn = New ADODB.Connection
cnn.Open "Provider=PRO; Data Source=SOURCE; Initial Catalog=CAT;" _
& "User Id=ID; Password=PW;"
If cnn.State = adStateOpen Then
MsgBox ("You have an established connection with the L&TD SQL Server Database and the CDData table has been uploaded to the server.")
Else
MsgBox ("Cannot connect to SQL Server. Data will be stored locally to CDData Table until application is opened again with an established connection.")
End
End If
On Error GoTo 0
' MsgBox ("Please wait while the database is updating, this may take a moment.")
End Function
As you can see, I placed an END before the END IF so if there is no connection it just ends altogether.
The UPLOAD code is
Public Function Update()
Dim cdb As DAO.Database, qdf As DAO.QueryDef
Dim rs As DAO.Recordset
Dim err As DAO.Error
' Const DestinationTableName = "AC_CDData"
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
qdf.SQL = "INSERT INTO AC_CDData_1(EmployeeID, EmployeeName, Region, District, Function1, Gender, EEOC, Division, Center, MeetingReadinessLevel, ManagerReadinessLevel, EmployeeFeedback, DevelopmentForEmployee1, DevelopmentForEmployee2, DevelopmentForEmployee3, DevelopmentForEmployee4, DevelopmentForEmployee5, Justification, Notes, Changed, JobGroupCode, JobDesc, JobGroup) " & _
"Values (" & _
"'" & rs!EmployeeID & "', " & _
"'" & rs!EmployeeName & "', " & _
"'" & rs!Region & "', " & _
"'" & rs!District & "', " & _
"'" & rs!Function1 & "', " & _
"'" & rs!Gender & "', " & _
"'" & rs!EEOC & "', " & _
"'" & rs!Division & "', " & _
"'" & rs!Center & "', " & _
"'" & rs!ManagerReadinessLevel & "', " & _
"'" & rs!MeetingReadinessLevel & "', " & _
"'" & rs!EmployeeFeedback & "', " & _
"'" & rs!DevelopmentForEmployee1 & "', " & _
"'" & rs!DevelopmentForEmployee2 & "', " & _
"'" & rs!DevelopmentForEmployee3 & "', " & _
"'" & rs!DevelopmentForEmployee4 & "', " & _
"'" & rs!DevelopmentForEmployee5 & "', " & _
"'" & rs!Justification & "', " & _
"'" & rs!Notes & "', " & _
"'" & rs!Changed & "', " & _
"'" & rs!JobGroupCode & "', " & _
"'" & rs!JobDesc & "', " & _
"'" & rs!JobGroup & "')"
qdf.ReturnsRecords = False
On Error GoTo Update_qdfError
qdf.Execute dbFailOnError
On Error GoTo 0
rs.MoveNext
Loop
rs.Close
Set qdf = Nothing
Set cdb = Nothing
Set rs = Nothing
Exit Function
Update_qdfError:
For Each err In DAO.Errors
MsgBox err.Description, vbCritical, "Error " & err.Number
Next
End Function
So is there a way I can modify the Connection code and add it to the update code (minus the message boxes) so if the connection cuts off it will terminate the code?

Did you try out transactions? Wrapping your insert script inside a transaction will not change the database until you've explicitly committed the transaction. If the data connection is lost during the inserts, the commit will never be called, and the SQL Server data won't be changed.
See http://msdn.microsoft.com/en-us/library/office/ff196400%28v=office.15%29.aspx

Related

No value given for one or more required parameter vb.net error

Im making a hotel billing system and I want to create a button for update a record in MS access database.
here is my code:
Dim cmd As New OleDbCommand("Update CheckInList set TransactionID='" & CombotransID.Text & "',FirstName='" & guesttextbox1.Text & "', MiddleName='" & guesttextbox2.Text & "',LastName='" & guesttextbox1.Text & "',RoomNumber='" & RoomTextBox1.Text & "',Numberofdays='" & txtDaysNumber.Text & "', Noofchildren='" & Noofadultstxtbox1.Text & "',NoofAdults='" & noofchildrentextbox2.Text & "',CheckinDate='" & TxtCheckInDate.Text & "',CheckoutDatee='" & dtCheckOutDate.Text & "', SubTotal='" & TxtSubTotal.Text & "',AmnitiesAddonns='" & Txtamnities.Text & "', TotalBalance='" & TxtTotal.Text & "' where TransactionID=" & CombotransID.Text & "", conn)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
MessageBox.Show("Record Update Successfully")
After that I run the program and got the error message "No value given for one or more required parameter" and I don't know how to fix on it.

Update Third Table While Looping Through Two Recordsets

I have the following code (which a very helpful person on here wrote based on a previous question). It loops through two tables to determine if an interview is valid and then loops though a gift card table for an unused card. This all works as expected. However, I now realize I need to add a new record to a third table (Receipts) everytime a card is assigned. I have tried using "INSERT INTO..." in the loop but it never puts anything into the Receipts table. The data going to the Receipts table will need to selected from both the Interviews table and the Giftcards table.
On Error GoTo E_Handle
Dim db As DAO.Database
Dim rsInterview As DAO.Recordset
Dim rsGiftcard As DAO.Recordset
Dim strSQL As String
Set db = CurrentDb
strSQL = "SELECT * FROM [SOR 2 UNPAID Intake Interviews]" _
& " WHERE InterviewTypeId='1' " _
& " AND ConductedInterview=1 " _
& " AND StatusId IN(2,4,5,8)" _
& " AND IsIntakeConducted='1' " _
& " ORDER BY InterviewDate ASC;"
Set rsInterview = db.OpenRecordset(strSQL)
If Not (rsInterview.BOF And rsInterview.EOF) Then
strSQL = "SELECT * FROM Giftcard_Inventory_Query" _
& " WHERE CardType=1 " _
& " AND Assigned=0 " _
& " AND Project=3 " _
& " ORDER BY DateAdded ASC, CompleteCardNumber ASC;"
Set rsGiftcard = db.OpenRecordset(strSQL)
If Not (rsGiftcard.BOF And rsGiftcard.EOF) Then
Do
rsGiftcard.Edit
rsGiftcard!DateUsed = Format(Now(), "mm/dd/yyyy")
rsGiftcard!Assigned = "1"
rsGiftcard.Update
db.Execute " INSERT INTO [SOR 2 Intake Receipts] " _
& "(PatientID,GiftCardType,GiftCardNumber,GiftCardMailedDate,InterviewDate,CreatedBy,GpraCollectorID) VALUES " _
& "(rsInterview!PatientID, rsGiftcard!CardType, rsGiftcard!CompleteCardNumber, Now(), rsInterview!InterviewDate, rsInterview!CreatedBy, rsInterview!GpraCollectorID);"
rsGiftcard.MoveNext
rsInterview.MoveNext
Loop Until rsInterview.EOF
End If
End If
sExit:
On Error Resume Next
rsInterview.Close
rsGiftcard.Close
Set rsInterview = Nothing
Set rsGiftcard = Nothing
Set db = Nothing
Exit Sub
E_Handle:
MsgBox Err.Description & vbCrLf & vbCrLf & "sAssignGiftCards", vbOKOnly + vbCritical, "Error: " & Err.Number
Resume sExit
I figured it out. Thanks to everyone who pushed me in the correct direction.
On Error GoTo E_Handle
Dim db As DAO.Database
Dim rsInterview As DAO.Recordset
Dim rsGiftcard As DAO.Recordset
Dim strSQL As String
Set db = CurrentDb
strSQL = "SELECT * FROM [SOR 2 UNPAID Intake Interviews]" _
& " WHERE InterviewTypeId='1' " _
& " AND ConductedInterview=1 " _
& " AND StatusId IN(2,4,5,8)" _
& " AND IsIntakeConducted='1' " _
& " ORDER BY InterviewDate ASC;"
Set rsInterview = db.OpenRecordset(strSQL)
If Not (rsInterview.BOF And rsInterview.EOF) Then
strSQL = "SELECT * FROM Giftcard_Inventory_Query" _
& " WHERE CardType=1 " _
& " AND Assigned=0 " _
& " AND Project=3 " _
& " ORDER BY DateAdded ASC, CompleteCardNumber ASC;"
Set rsGiftcard = db.OpenRecordset(strSQL)
If Not (rsGiftcard.BOF And rsGiftcard.EOF) Then
Do
rsGiftcard.Edit
rsGiftcard!DateUsed = Format(Now(), "mm/dd/yyyy")
rsGiftcard!Assigned = "1"
rsGiftcard.Update
db.Execute " INSERT INTO [SOR 2 Intake Receipts] " _
& "(PatientID,GiftCardType,GiftCardNumber,GiftCardMailedDate,InterviewDate,CreatedBy,GpraCollectorID) VALUES " _
& "('" & rsInterview("PatientID") & "', '" & rsGiftcard("CardType") & "', '" & rsGiftcard("CompleteCardNumber") & "', Now(), '" & rsInterview("InterviewDate") & "', '" & rsInterview("CreatedBy") & "', '" & rsInterview("GpraCollectorID") & "');"
rsGiftcard.MoveNext
rsInterview.MoveNext
Loop Until rsInterview.EOF
End If
End If
sExit:
On Error Resume Next
rsInterview.Close
rsGiftcard.Close
Set rsInterview = Nothing
Set rsGiftcard = Nothing
Set db = Nothing
Exit Sub
E_Handle:
MsgBox Err.Description & vbCrLf & vbCrLf & "sAssignGiftCards", vbOKOnly + vbCritical, "Error: " & Err.Number
Resume sExit

Access VBA using SQL UPDATE

I'm using two Access databases (front end and back end).
My code for query work, but I get it to work with updating the database. What am I doing wrong?
I get a runtime error 3078 for the DoCmd.RunSQL strSql on line 25.
Set cnn = CreateObject("ADODB.Connection")
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & CurrentProject.Path & "\DB_Cryk.accdb"
cnn.Open strConnection
MemberID = txtMemberID.Value
strSql = "UPDATE Cryk " & _
"SET Membership = '" & txtMembership.Value & "', " & _
" Memberstatus = '" & txtMemberstatus.Value & "', " & _
" Membername = '" & txtMembername.Value & "', " & _
" Memberaddress = '" & txtMemberaddress.Value & "', " & _
" Memberzip = '" & txtMemberzip.Value & "', " & _
" Membercity = '" & txtMembercity.Value & "', " & _
" Memberphone = '" & txtMemberphone.Value & "', " & _
" Membermail = '" & txtMembermail.Value & "', " & _
" Memberyear = '" & txtMemberyear.Value & "', " & _
" Dateofbirth = '" & txtDateofbirth.Value & "', " & _
" Memberno = '" & txtMemberno.Value & "', " & _
" Memberfee = '" & txtMemberfee.Value & "', " & _
" Memberpayment = '" & txtMemberpayment.Value & "'" & _
"WHERE MemberID= '" & MemberID & "'"
DoCmd.RunSQL strSql
cnn.Close
Set cnn = Nothing
Error 3078 indicates that the target table does not exist in your database.
Note that, although you open an ADO connection to the database DB_Cryk.accdb, you execute your SQL statement using the DoCmd.RunSQL method, which operates on the current database.
Instead, if you want the SQL to be executed in your DB_Cryk.accdb database, you should use the Execute method of the ADODB Connection object, e.g.:
cnn.Execute strsql
Where query parameterization is concerned, you may wish to refer to this superb answer, specifically, the 'Using ADO' section.

Missing comma error error inserting sql through access 2010 vba

Having the weirdest problem ever. I do have an sql insert statement, that properly works in sql. When i put that sql into vba it works very good from my pc. However, it does not work and shows sql error: missing comma. Where can be the problem??? I use Access 2010 plus, others use same Access version and having same ODB connections (DSN servers) . Some code example:
sql = "Driver={Microsoft ODBC for Oracle}; " & _
"CONNECTSTRING=(DESCRIPTION=" & _
"(ADDRESS=(PROTOCOL=TCP)" & _
"(HOST= ODB)(PORT=1520))" & _
"(CONNECT_DATA=(SERVICE_NAME=ABTL))); uid=IN; pwd=XXX;"
Set con = New ADODB.Connection
Set rec = New ADODB.Recordset
Set cmd = New ADODB.Command
con.Open sql
Set db = CurrentDb()
Set rst = db.OpenRecordset(strSQL)
Do While Not rst.EOF
insetSQL = con.Execute(" INSERT INTO STOCK (PNM_AUTO_KEY, PN, DESCRIPTION, HISTORICAL_FLAG, qty_oh, qty_adj, qty_available, CTRL_NUMBER, CTRL_ID, receiver_number, rec_date, serial_number,pcc_auto_key, cnc_auto_key, loc_auto_key, whs_auto_key, unit_cost, adj_cost, stc_auto_key, visible_mkt, remarks, ifc_auto_key, exp_date, unit_price, tagged_by, tag_date, owner, PART_CERT_NUMBER,ORIGINAL_PO_NUMBER, SHELF_LIFE, CTS_AUTO_KEY, MFG_LOT_NUM, AIRWAY_BILL )" & _
" VALUES ( " & rst![minimumas] & ", '" & rst![pn] & "', '" & "FROM_SCRIPT" & "', '" & "F" & "'," & rst![qty_oh] & "," & rst![qty_oh] & "," & rst![qty_oh] & "," & "G_STM_CTRL_NUMBER.nextval" & "," & "1" & ", '" & rst![receiver_number] & "', " & " TO_DATE('" & rst![rec_date] & "','YYYY-MM-DD'), '" & rst![serial_number] & "'," & rst![pcc_auto_key] & "," & rst![cnc_auto_key] & "," & rst![loc_auto_key] & "," & rst![whs_auto_key] & "," & rst![unit_cost] & "," & rst![unit_cost] & "," & "1" & ",'" & "T" & "', '" & rst![remarks] & "'," & _
"1" & ", " & " TO_DATE('" & rst![exp_date] & "','YYYY-MM-DD'), " & "0" & ",'" & rst![TAGGED_BY] & "', " & " TO_DATE('" & rst![tag_date] & "','YYYY-MM-DD'), '" & "" & "', '" & rst![PART_CERT_NUMBER] & "', '" & rst![ORIGINAL_PO_NUMBER] & "', '" & rst![SHELF_LIFE] & "', " & rst![CERT_SOURCE] & ", '" & rst![MFG_LOT_NUM] & "', '" & rst![AIRWAY_BILL] & "'" & " )")
Loop
It might be that one of the rescordset fields that is a string data type, has a value that contains a comma but you have not treated it as string.
eg
VALUES ( " & rst![minimumas] & ",
For the above code to work minimumas CANNOT contain any commas.
Are you certain that all the string fields int he recordset have been appended to the SQL string with a ' around them.
We need to see the sql string is created which then causes the error. Please provide this as requested.
=========================================================
PART 2 Viewing the SQL causing the error
replace
insetSQL = con.Execute(
with
on error resume next
strMySQl = the string currently used in the execute statement
insetSQL = con.Execute(strMySQl)
if err.number <> 0 then
stop
debug.print err.number, err.description
debug.print strMySQl
end if
then post the sql string that is printed in the immediate window to this site.
I would also suggest that you compare the SQL string generated on your machine with the other machines - just in case something weird is happening.

vbscript that enters SQL and prints selected values to .txt file

I'm trying to connect to a SQL server(localhost) and extract the following:
SELECT INVOICENO, SUPPLIERID, AMOUNT, DOCID
FROM ES_TRANS_HEADER
WHERE READYTOINVOICE = 1
I then need to get this information into a .txt file, seperated by commas
This is what I got so far:
function accounting()
Dim myStream, connection, myCommand, recValue
Set myStream = CreateObject("ADODB.Stream")
Set connection = CreateObject("ADODB.Connection")
Set myCommand = CreateObject("ADODB.Command")
connection.Open "Provider=SQLNCLI10;" & _
"Data Source=localhost;" & _
"Integrated Security=SSPI;" & _
"Initial Catalog=SQLDatabase;" & _
"User ID=;Password="
myCommand.ActiveConnection=connection
myCommand.CommandText="SELECT INVOICENO,SUPPLIERID, AMOUNT, DOCID FROM ES_TRANS_HEADER WHERE READYTOINVOICE = 1"
SET recValue = myCommand.Execute()
If Not recValue.EOF then
MsgBox "INVOICENO = " & recValue(0) & vbcrlf & "SUPPLIERID=" & recValue(1) _
& "AMOUNT=" & recValue(2) & "DOCID=" & recValue(3)
End If
While Not recValue.EOF
INVOICENO = recValue(0)
SUPPLIERID = recValue(1)
AMOUNT = recValue(2)
DOCCID = recValue(3)
recValue.MoveNext
Wend
end function
Am I on the right track here, and if so what should I try to do next?
Thanks in advance
MsgBox didn't have any parentheses missing. Remove them (and read Eric Lippert's most awesome blog post on parentheses in VBScript). What's missing in that line is a line continuation character (_) at the end of the line. In VBScript you cannot wrap lines without that. Change this:
MsgBox ("INVOICENO = " & recValue(0) & vbcrlf & "SUPPLIERID=" & recValue(1)
& "AMOUNT=" & recValue(2) & "DOCID=" & recValue(3))
into this:
MsgBox "INVOICENO = " & recValue(0) & vbcrlf & "SUPPLIERID=" & recValue(1) _
& "AMOUNT=" & recValue(2) & "DOCID=" & recValue(3)
or put the whole statement in a single line:
MsgBox "INVOICENO = " & recValue(0) & vbcrlf & "SUPPLIERID=" & recValue(1) & "AMOUNT=" & recValue(2) & "DOCID=" & recValue(3)
As for the database connection, your connection string seems odd. According to the information provided here that connection string is for connections to a mirrored database. Try this instead:
db = "..." 'specify database name here
connection.Open "Provider=SQLNCLI10;" _
& "Server=localhost;" _
& "Database=" & db & ";" _
& "Trusted_Connection=yes;"
If that doesn't help: check the value of the connection's State property:
WScript.Echo connection.State
Also, update your question with any error you're getting (error number, error message and line number).