Need Help for Updating database in vb.net - sql

Someone knows why I got an exception when the code running at cmd.ExecuteNonQuery()? when I update Date, it runs perfectly but when I update the Finish date, I got that error.
This is the code
Call connection()
If txt_UpCom.Text = "" Or cbCom.SelectedItem = "" Then
If txt_ComNew.Enabled = True Then
MessageBox.Show("Please fill the entire data!")
End If
Else
Try
Dim str As String
If cbCom.SelectedItem = "Date" Or cbCom.SelectedItem = "Finish Date" Then
Dim comdate As String = dateCom.Value.ToString("yyyy-MM-dd")
str = "UPDATE complain SET " & cbCom.SelectedItem & "= '" & comdate & "' WHERE ComplainID = '" & txt_UpCom.Text & "'"
Else
str = "UPDATE complain SET " & cbCom.SelectedItem & " = '" & txt_ComNew.Text & "' WHERE ComplainID = '" & txt_UpCom.Text & "'"
End If
cmd = New MySql.Data.MySqlClient.MySqlCommand(str, conn)
cmd.ExecuteNonQuery()
msgBoxSuccess.ShowDialog()
conn.Close()
Catch ex As Exception
MessageBox.Show("Unable to Update")
End Try
End If
This is the table in database

As #Jacek Wróbel mentioned in the comments, you should keep the column names between [] (square brackets) or "" (double quots). The same thing goes for table names (or any other SQL objects for that matter).
Long story short, change this part of your code:
If cbCom.SelectedItem = "Date" Or cbCom.SelectedItem = "Finish Date" Then
Dim comdate As String = dateCom.Value.ToString("yyyy-MM-dd")
str = "UPDATE complain SET " & cbCom.SelectedItem & "= '" & comdate & "' WHERE ComplainID = '" & txt_UpCom.Text & "'"
Else
str = "UPDATE complain SET " & cbCom.SelectedItem & " = '" & txt_ComNew.Text & "' WHERE ComplainID = '" & txt_UpCom.Text & "'"
End If
to this:
If cbCom.SelectedItem = "Date" Or cbCom.SelectedItem = "Finish Date" Then
Dim comdate As String = dateCom.Value.ToString("yyyy-MM-dd")
str = "UPDATE `complain` SET `" & cbCom.SelectedItem & "` = '" & comdate & "' WHERE `ComplainID` = '" & txt_UpCom.Text & "'"
Else
str = "UPDATE `complain` SET `" & cbCom.SelectedItem & "` = '" & txt_ComNew.Text & "' WHERE `ComplainID` = '" & txt_UpCom.Text & "'"
End If
Note: I prefer to keep things consistant, so I added [] to each object whether it contains spaces or not.

Related

UPDATE Query in MS Access using SQL in VBA with declared strings

been a while since I've posted so please forgive any formatting issues. Looking to update a table field with a value from another record in the same field in the same table.
I've declared two strings, and the strDeal string is coming back with the correct values when debugging. However when I introduce the string into the sql statement I can't the query to update the field. I'm not sure exactly what isn't working correctly, so any help would be appreciated.
The basics are I'm trying to update the Case_Qty field with a value from the same field in the same table based on the returned value from a subquery. Thanks!
Dim strDeal As String
Dim strSQL As String
strDeal = DMax("[Deal_No]", "[tblStructuresNoDAworking]", "[Structure_Name] = Forms!frmStructNoDASetup!Structure_Name AND [FG_Ind] = 0 AND [Deal_No] < Forms!frmStructNoDASetup!Deal_No")
strSQL = "UPDATE tblStructuresNoDAworking SET tblStructuresNoDAworking.Case_Qty = (SELECT [Case_Qty] FROM tblStructuresNoDAworking WHERE [Structure_Name] = '" & Me.Structure_Name.Value & "' AND [Deal_No] = '" & strDeal & "') WHERE [Structure_Name] = '" & Me.Structure_Name.Value & "' AND [Deal_No] = '" & Me.Deal_No.Value & "'"
DoCmd.RunSQL (strSQL)
Try this where you concatenate the values from the form:
Dim strDeal As String
Dim strSQL As String
strDeal = DMax("[Deal_No]", "[tblStructuresNoDAworking]", "[Structure_Name] = '" & Forms!frmStructNoDASetup!Structure_Name & "' AND [FG_Ind] = 0 AND [Deal_No] < '" & Forms!frmStructNoDASetup!Deal_No & "'")
strSQL = "UPDATE tblStructuresNoDAworking " & _
"SET tblStructuresNoDAworking.Case_Qty = " & _
" (SELECT [Case_Qty] " & _
" FROM tblStructuresNoDAworking " & _
" WHERE [Structure_Name] = '" & Me.Structure_Name.Value & "' AND [Deal_No] = '" & strDeal & "') " & _
"WHERE [Structure_Name] = '" & Me.Structure_Name.Value & "' AND [Deal_No] = '" & Me.Deal_No.Value & "'"
DoCmd.RunSQL strSQL
For numeric Deal:
Dim Deal As Long
Dim strSQL As String
Deal = DMax("[Deal_No]", "[tblStructuresNoDAworking]", "[Structure_Name] = '" & Forms!frmStructNoDASetup!Structure_Name & "' AND [FG_Ind] = 0 AND [Deal_No] < '" & Forms!frmStructNoDASetup!Deal_No & "'")
strSQL = "UPDATE tblStructuresNoDAworking " & _
"SET tblStructuresNoDAworking.Case_Qty = " & _
" (SELECT [Case_Qty] " & _
" FROM tblStructuresNoDAworking " & _
" WHERE [Structure_Name] = '" & Me.Structure_Name.Value & "' AND [Deal_No] = " & Deal & ") " & _
"WHERE [Structure_Name] = '" & Me.Structure_Name.Value & "' AND [Deal_No] = " & Me.Deal_No.Value & ""
DoCmd.RunSQL strSQL

How concatenate recordset variables to use filter method - Vba

I would like to concatenate multiple variables on my recordset filter. Here more information :
rs is recordset
titre can be M. or Mme or S. (come from rs)
Nom is of the form (come from rs) : FirstName LastName (with space between)
but I can't. I tried :
space = " "
rs.Filter = "[titre+ space + Nom] = '" & oLookFullName & "' and nomEntreprise = '" & objContact.CompanyName & "'"
Concatenation = rs!titre + " " + rs!Nom
rs.Filter = "Concatenation = '" & oLookFullName & "'"
Any ideas ?
EDIT
#Gustav, I tried your code with split and it seems the filter contains the correct value but just after I have this if loop and in this case rs.EOF is true while the contact exists... why ?
If rs.EOF Then 'Or (rs.BOF = True) Then
Debug.Print oLookFullName & " is not found."
End If
Try with:
rs.Filter = "[titre] & ' ' & [Nom] = '" & oLookFullName & "' And [nomEntreprise] = '" & objContact.CompanyName & "'"
or:
rs.Filter = "[titre] = '" & Split(oLookFullName, " ")(0) & "' And [Nom] = '" & Split(oLookFullName, " ")(1) & "' And [nomEntreprise] = '" & objContact.CompanyName & "'"

VBA error matching date from table and date from query when date has leading zero eg 01/04 or 02/04

I have a query in MS Access called qryRMCountStudentsBySessionWP. The results are shown below.
I have some VBA code shown below. Basically if the Timetable_Date, Timetable_Session and Location match Exam_Date, Exam_Session and Exam_Location of a record in a table called Invigilation, then changes are made to that record's start time.
This works fabulously for 30/03/2020 and 31/03/2020 but not any of the April dates. I think this is because of leading zeros but I just can't figure out how to fix it. Any ideas?
Private Sub wordProcessing()
Dim dbs As Database
Dim name As String
Dim SQL As String
Dim rstAllSessions As Recordset
Set dbs = CurrentDb
SQL = "SELECT Timetable_Date, Timetable_Session, Location, CountOfStudent_Ref FROM qryRMCountStudentsBySessionWP;"
Set rstAllSessions = dbs.OpenRecordset(SQL)
rstAllSessions.MoveFirst
Do Until rstAllSessions.EOF ' for each sesson update invigilation table
If rstAllSessions.Fields(3) >= 10 Then
If rstAllSessions.Fields(1) = "A" Then
dbs.Execute "UPDATE Invigilation SET Start_Time = TimeValue('08:30:00'), Notes = 'WP Exam with 10 or more students' WHERE Invigilation.Exam_Date = #" & rstAllSessions!Timetable_Date & "# AND Invigilation.Exam_Location = " & "'" & rstAllSessions!Location & "'" & "AND Invigilation.Exam_Session = " & "'" & rstAllSessions!Timetable_Session & "'" & ";", dbFailOnError
Else
dbs.Execute "UPDATE Invigilation SET Start_Time = TimeValue('13:00:00'), Notes = 'WP Exam with 10 or more students' WHERE Invigilation.Exam_Date = #" & rstAllSessions!Timetable_Date & "# AND Invigilation.Exam_Location = " & "'" & rstAllSessions!Location & "'" & "AND Invigilation.Exam_Session = " & "'" & rstAllSessions!Timetable_Session & "'" & ";", dbFailOnError
End If
ElseIf rstAllSessions.Fields(3) >= 5 Then
If rstAllSessions.Fields(1) = "A" Then
dbs.Execute "UPDATE Invigilation SET Start_Time = TimeValue('08:35:00'), Notes = 'WP Exam with 5 or more students' WHERE Invigilation.Exam_Date = #" & rstAllSessions!Timetable_Date & "# AND Invigilation.Exam_Location = " & "'" & rstAllSessions!Location & "'" & "AND Invigilation.Exam_Session = " & "'" & rstAllSessions!Timetable_Session & "'" & ";", dbFailOnError
Else
dbs.Execute "UPDATE Invigilation SET Start_Time = TimeValue('13:05:00'), Notes = 'WP Exam with 5 or more students' WHERE Invigilation.Exam_Date = #" & rstAllSessions!Timetable_Date & "# AND Invigilation.Exam_Location = " & "'" & rstAllSessions!Location & "'" & "AND Invigilation.Exam_Session = " & "'" & rstAllSessions!Timetable_Session & "'" & ";", dbFailOnError
End If
ElseIf rstAllSessions.Fields(3) > 1 Then
If rstAllSessions.Fields(1) = "A" Then
dbs.Execute "UPDATE Invigilation SET Start_Time = TimeValue('08:40:00'), Notes = 'WP Exam with >1 and <5 students' WHERE Invigilation.Exam_Date = #" & rstAllSessions!Timetable_Date & "# AND Invigilation.Exam_Location = " & "'" & rstAllSessions!Location & "'" & "AND Invigilation.Exam_Session = " & "'" & rstAllSessions!Timetable_Session & "'" & ";", dbFailOnError
Else
dbs.Execute "UPDATE Invigilation SET Start_Time = TimeValue('13:10:00'), Notes = 'WP Exam with >1 and <5 students' WHERE Invigilation.Exam_Date = #" & rstAllSessions!Timetable_Date & "# AND Invigilation.Exam_Location = " & "'" & rstAllSessions!Location & "'" & "AND Invigilation.Exam_Session = " & "'" & rstAllSessions!Timetable_Session & "'" & ";", dbFailOnError
End If
Else
If rstAllSessions.Fields(1) = "A" Then
dbs.Execute "UPDATE Invigilation SET Start_Time = TimeValue('08:45:00'), Notes = 'WP Exam with 1 student' WHERE Invigilation.Exam_Date = #" & rstAllSessions!Timetable_Date & "# AND Invigilation.Exam_Location = " & "'" & rstAllSessions!Location & "'" & "AND Invigilation.Exam_Session = " & "'" & rstAllSessions!Timetable_Session & "'" & ";", dbFailOnError
Else
dbs.Execute "UPDATE Invigilation SET Start_Time = TimeValue('13:15:00'), Notes = 'WP Exam with 1 student' WHERE Invigilation.Exam_Date = #" & rstAllSessions!Timetable_Date & "# AND Invigilation.Exam_Location = " & "'" & rstAllSessions!Location & "'" & "AND Invigilation.Exam_Session = " & "'" & rstAllSessions!Timetable_Session & "'" & ";", dbFailOnError
End If
End If
' doesn't do dates with leading 0s?????
rstAllSessions.MoveNext
Loop
rstAllSessions.Close
dbs.Close
End Sub
Date values are numeric, thus no leading zeroes. But you must pass properly formatted string expressions for the date values when concatenating:
"UPDATE Invigilation SET Start_Time = TimeSerial(13,15,0), Notes = 'WP Exam with 1 student' WHERE Invigilation.Exam_Date = #" & Format(rstAllSessions!Timetable_Date, "yyyy\/mm\/dd") & "# AND Invigilation.Exam_Location = '" & rstAllSessions!Location & "' AND Invigilation.Exam_Session = '" & rstAllSessions!Timetable_Session & "';"

How to fix update code using short text as data type

Hello I just want to ask about my code. Why its showing error if I change the data type of ID_NO in short text? Btw database that I'm using is MS ACCESS
Dim i As Integer
i = dgMembers.CurrentRow.Index
currentid = dgMembers.Item(1, i).Value.ToString()
ds = New DataSet
adapter = New OleDbDataAdapter("update [FASA_MembersAccount] set ID_No = '" & txtMemberIDNo.Text & "',[FirstName] = '" & txtMemberFirstName.Text & "',[LastName] ='" & txtMemberLastName.Text & "',[Mobile_No] = '" & txtMemberMobileNo.Text & "',[Gender] = '" & cbMemberGender.Text & "',[Birthday] = '" & dtpMember.Text & "',[Password] = '" & txtMemberPassword.Text & "',[Address] = '" & txtMemberAddress.Text & "' where ID_No = " & currentid, conn)
adapter.Fill(ds, "FASA_MembersAccount")
Can somebody help me?
Here's an example of how to get your SQL code so you can run it in your database to check for syntax errors. Does this help?
Dim i As Integer
Dim strSQL as string
i = dgMembers.CurrentRow.Index
currentid = dgMembers.Item(1, i).Value.ToString()
ds = New DataSet
strSQL = "update [FASA_MembersAccount] set ID_No = '" & txtMemberIDNo.Text & "',[FirstName] = '" & txtMemberFirstName.Text & "',[LastName] ='" & txtMemberLastName.Text & "',[Mobile_No] = '" & txtMemberMobileNo.Text & "',[Gender] = '" & cbMemberGender.Text & "',[Birthday] = '" & dtpMember.Text & "',[Password] = '" & txtMemberPassword.Text & "',[Address] = '" & txtMemberAddress.Text & "' where ID_No = " & currentid
'--- Set your breakpoint here and use the immediate window to ?strSQL then copy/paste your command into ms-access
adapter = New OleDbDataAdapter(strSQL, conn)
adapter.Fill(ds, "FASA_MembersAccount")

Excel VBA Selecting Records from Access Database Not Pulling Correctly

I have a macro that pulls from an Access DB and writes the recordset to the spreadsheet based upon dates that are entered into a userform. However, if I enter in "3/2/2105" and "3/5/2015" it returns all the records from 3/2-3/5 and then 3/20-3/31. I cannot think of any reason why it would do this. If anybody could point me in the right direction/make suggestions it would be greatly appreciated.
Sub pullfrommsaccess()
queryform.Show
Dim conn As Object
Dim rs As Object
Dim AccessFile As String
Dim SQL As String
Dim startdate As String
Dim enddate As String
Dim i As Integer
Sheet2.Cells.Delete
Application.ScreenUpdating = False
AccessFile = ThisWorkbook.Path & "\" & "mdidatabase.accdb"
On Error Resume Next
Set conn = CreateObject("ADODB.connection")
If Err.Number <> 0 Then
MsgBox "Connection was not created!", vbCritical, "Connection Error"
Exit Sub
End If
On Error GoTo 0
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & AccessFile
If tblname = "Attainments" Then
If shift1 = "1" Then
SQL = "SELECT [Line],[Area],[Shift],[Attainment Percentage],[Date] FROM " & tblname & " WHERE Shift='1' and Date Between " & "'" & pastdate & "' " & "and" & " '" & currentdate & "'"
End If
If shift2 = "2" Then
SQL = "SELECT [Line],[Area],[Shift],[Attainment Percentage],[Date] FROM " & tblname & " WHERE Shift='2' and Date Between " & "'" & pastdate & "' " & "and" & " '" & currentdate & "'"
End If
If shift1 = "1" And shift2 = "2" Then
SQL = "SELECT [Line],[Area],[Shift],[Attainment Percentage],[Date] FROM " & tblname & " WHERE Date Between " & "'" & pastdate & "' " & "and" & " '" & currentdate & "'"
End If
End If
If tblname = "MDItable" Then
If shift1misses = "1" Then
SQL = "SELECT [Date],[Area],[Shift],[Line],[Quantity],[Issue] FROM " & tblname & " WHERE Shift='1' and Date Between " & "'" & pastdatemisses & "' " & "and" & " '" & currentdatemisses & "'"
End If
If shift2misses = "2" Then
SQL = "SELECT [Date],[Area],[Shift],[Line],[Quantity],[Issue] FROM " & tblname & " WHERE Shift='2' and Date Between " & "'" & pastdatemisses & "' " & "and" & " '" & currentdatemisses & "'"
End If
If shift1misses = "1" And shift2misses = "2" Then
SQL = "SELECT [Date],[Area],[Shift],[Line],[Quantity],[Issue] FROM " & tblname & " WHERE Date Between " & "'" & pastdatemisses & "' " & "and" & " '" & currentdatemisses & "'"
End If
End If
On Error Resume Next
Set rs = CreateObject("ADODB.Recordset")
If Err.Number <> 0 Then
Set rs = Nothing
Set conn = Nothing
MsgBox "Recordset was not created!", vbCritical, "Recordset Error"
Exit Sub
End If
On Error GoTo 0
rs.CursorLocation = 3
rs.CursorType = 1
rs.Open SQL, conn
If rs.EOF And rs.BOF Then
rs.Close
conn.Close
Set rs = Nothing
Set conn = Nothing
Application.ScreenUpdating = True
MsgBox "There are no records in the recordset!", vbCritical, "No Records"
Exit Sub
End If
For i = 0 To rs.Fields.Count - 1
Sheet2.Cells(1, i + 1) = rs.Fields(i).Name
Next i
'Copy From RecordSet to Excel and Reset
Sheet2.Range("A2").CopyFromRecordset rs
rs.Close
conn.Close
Set rs = Nothing
Set conn = Nothing
MsgBox "The records from " & pastdate & " and " & currentdate & " were successfully retrieved from the '" & tblname & "' table!", vbInformation, "Done"
End If
Call TrimALL
End Sub
You have a field named Date, try renaming that and reworking the code as in first instance that's a reserved word and is a bad idea for starters!
When working with dates, see Allen Browne's comments on the matter here for consistency;
http://allenbrowne.com/ser-36.html
You have your dates declared as string, but in your SQL query you're surrounding them with a ' not a #. It should read;
Date Between " & "#" & pastdate & "# " & "and" & " #" & currentdate & "#"
All of the above should sort you out, if not comment and I'll take a much closer look for you!