Why this statement cannot be updated in the database - mysql

I am facing this issue with my query. I would like you to kindly help me resolve it.
MD = "UPDATE librarysystem.audit set timeout = '" & Today + "" + TimeOfDay & "' AND status='0' WHERE username = '" & AccountId & "'AND status = '1'"
cmd = New MySqlCommand(MD, con)
cmd.ExecuteNonQuery()
here's the code:
connect()
Dim result As Integer = MessageBox.Show("Are You Sure You Want To LOGOUT?", "Are You?", MessageBoxButtons.YesNo)
If result = DialogResult.No Then
Me.Show()
ElseIf result = DialogResult.Yes Then
connect()
Dim time As DateTime
time = Date.Today
Dim a As Integer = 0
MD = "UPDATE librarysystem.audit set timeout = '" & Today + "" + TimeOfDay & "' AND status='0' WHERE username = '" & AccountId & "'AND status = '1'"
cmd = New MySqlCommand(MD, con)
cmd.ExecuteNonQuery()
AccountSettings.Hide()
BorrowedBooks.Hide()
LogHistory.Hide()
Login.Hide()
ReturnedBooks.Hide()
SearchBooks.Hide()
End If
End Sub
:
Thank you in advance ^^

One of the deep hassles of SQL is that you're usually embedding one language in another. That makes it hard to read things in both languages clearly. Here's your SQL extracted from your vb.
UPDATE librarysystem.audit
set timeout = '" & Today + "" + TimeOfDay & "'
AND status='0'
WHERE username = '" & AccountId & "'AND status = '1'"
Here it is with some sample values substituted
UPDATE librarysystem.audit
set timeout = '2016-11-26 13:14:15'
AND status='0'
WHERE username = 'SomeUserName'AND status = '1'
You should be able to carry out that statement directly on your dbms and have it function correctly. But, look it over. What do you see?
I see an AND where there should be a , in the list of columns to update. AND only works in WHERE and ON clauses, not in lists of columns.
I see a missing space in the SQL in the sequence 'SomeUserName'AND.
I also see some potential confusion in the way your vb program created the value for timeout. It's not immediately clear whether your vb TimeOfDay variable will render in 24h format (13:14:15) or in am/pm format (01:14:15 PM).
Finally, I see an extraordinarily common mistake. The SQL statement is jammed onto one line, as if it had been written in the 1980s by a psychotic APL programmer. This makes your language-in-a-language program almost impossible to read.

Related

Updating Issues with MySQL and Access

So this is a problem which started happening a day ago.
I have an Access database file which stores a form for creating jobs, updating job sector, and deleting it from the MySQL table.
There are two tables that are used for this form: a local one stored in Access called "Job Route" and another through MYSQL ODBC Driver, ANSI 5.3 version called "To Do". The local table stores user-submitted data containing information on all job areas and state, while the MYSQL table only shows one job area at a time.
When a new entry is created, the text box details from the Access form are being stored onto both tables. Where each job contains up to 4 different sectors (e.g. [start date], [area1], [person in charge 1], [description1], ... [area4], [person in charge 4], [description4]). Whenever the data is being updated to its next state, in the local table only the job counter field is incremented, while every field in the MYSQL table called "To Do" is updated to its next state fields.
Connection to the server is good, and everything was running fine until an issue popped up in the updating function.
Basically how that function works is that on a listbox control, all current job data is being queried from the "To Do" table. The user selects an entry, and hits a button which loads the next sector information data from "Job Route", onto various textbox controls. The user can change those textbox inputs if they want - the only thing that is changed when the function runs is the "To Do". The information in "Job Route" remains the same. When the user hits the update button, the next sector field data is updated to "To Do", while only a counter in "Job Route" is being incremented to signify the current sector.
My problem is this. For the most part almost everything is running fine, but for one of the fields in "To Do" table does not update with the values it should from the textbox. So for instance if the textbox control was set to "Wyntile", the field name should be set to that, but for some reason a different value shows up instead, example="Apples". Here is the code:
Private Sub moveJob2_Click()
'get the job number
JobNum = Text31
CurrArea = DLookup("[Area]", "[To_Do]", "[Job_Number] =""" & JobNum & """")
area1 = DLookup("[Area1]", "[Job Route]", "[Job Number] =""" & JobNum & """")
area2 = DLookup("[Area2]", "[Job Route]", "[Job Number] =""" & JobNum & """")
area3 = DLookup("[Area3]", "[Job Route]", "[Job Number] =""" & JobNum & """")
area4 = DLookup("[Area4]", "[Job Route]", "[Job Number] =""" & JobNum & """")
'get what the current area is
Current = DLookup("[Current]", "[Job Route]", "[Job Number] =""" & JobNum & """")
'if the current area is the first area then check to make sure there is a second
'if so, then set the new area to it
If Current = 1 Then
If area2 = "---" Then
MsgBox area1 + " was the last area in the route. The job cannot be moved."
Exit Sub
End If
newArea = area2
ElseIf Current = 2 Then
If area3 = "---" Then
MsgBox area2 + " was the last area in the route. The job cannot be moved."
Exit Sub
End If
newArea = area3
ElseIf Current = 3 Then
If area4 = "---" Then
MsgBox area3 + " was the last area in the route. The job cannot be moved."
Exit Sub
End If
newArea = area4
Else
MsgBox area4 + " was the last area in the route. The job cannot be moved."
Exit Sub
End If
'set up link to both the To_Do and Job Route tables
Dim dbJobNumbers As DAO.Database
Dim rstJob As DAO.Recordset
Dim jobRoute As DAO.Recordset
Set dbJobNumbers = CurrentDb
Set rstJob = dbJobNumbers.OpenRecordset("To_Do")
Set jobRoute = dbJobNumbers.OpenRecordset("Job Route")
' >> Edit the job in the To_Do table
****' ERROR: Out of all these, only [Person_In_Charge] is being set to something
****' completely different from Text33, which wasn't changed by the user.
rstJob.FindFirst "[Job_Number]=""" + Text31 + """"
rstJob.Edit
rstJob("[Area]").Value = newArea
rstJob("[Person_In_Charge]").Value = Text33
rstJob("[Equipment]").Value = Text37
rstJob("[Description]").Value = Text35
rstJob.Update
'update the current area for the Job Route
jobRoute.FindFirst "[Job Number]=""" + Text31 + """"
jobRoute.Edit
jobRoute("[Current]").Value = CInt(Current) + 1
jobRoute.Update
'success message
MsgBox Text31 + " has been moved from " + CurrArea + " to " + newArea + "."
'requery the listboxes
Dim selectParas As String
selectParas = "SELECT [a].[Job_Number] as [Job Number], [a].[Description], [a].[Person_In_Charge] as [Person in Charge], [a].[Area] " & _
" FROM [To_Do] As [a];"
listRemoveJobs.RowSource = selectParas
listRemoveJobs.Requery
listChangeJobArea.RowSource = selectParas
listChangeJobArea.Requery
End Sub
The function has been running fine, and even now when I test it again it runs as programmed. Though today I recieved the "ODBC Insert on 'To Do' has failed" error, but that's for a different function. So I was thinking that something is wrong in the ODBC connection/MySQL table, but when I checked the table in phpmyadmin for the most part that table follows a similar format of other mysql tables used in Access.
Also to note, the person who had told me this issue runs on an old Windows XP version, where once before on that computer there were known issues of the defined OBDC ANSI 5.3 Driver instance completely disappearing from Access' Data Source list before. (The driver is still installed on Windows). That time, apparently the driver instance later re-appeared again magically in the D.S. list when that computer was restarted. ... I know this is rather long, but I can't seem to find the cause of why this updating error in Access is happening. Is there a known issue of ODBC having stability issues in connection? Why is the value changed to something completely different on update? Any insight would be appreciated.
While there is no reproducible example to help with your specific situation, consider running pure SQL UPDATE queries with binded parameters. Your area conditional logic can be rewritten into nested IIF expression. Possibly, this will simplify your problem and streamline your needs without DLookup or multiple recordset updates. Also, your re-assignment to RowSource is not necessary. Below utilizes parameterization, a best practice when running SQL in application layer:
SQL (save both below as Access queries)
mySavedJoinUpdateQuery
PARAMETERS Text33Param Text(255), Text35Param Text(255)
Text37Param Text(255), JobNumberParam Text(255);
UPDATE [To_Do] d
INNER JOIN [Job Route] r
ON d.Job_Number = r.Job_Number
SET [Area] = IIF([Current] = 1 AND [Area2] != '---', [Area2],
IIF([Current] = 2 AND [Area3] != '---', [Area3],
IIF([Current] = 3 AND [Area4] != '---', [Area4], [Area1)
)
),
[Person_In_Charge] = Text33Param,
[Equipment] = Text37Param,
[Description] = Text35Param
WHERE r.[Job Number] = JobNumberParam;
mySavedSimpleUpdateQuery
PARAMETERS JobNumberParam Text(255);
UPDATE [Job Route] r
SET r.[Current] = r.[Current] + 1
WHERE r.[Job Number] = JobNumberParam;
VBA
Private Sub moveJob2_Click()
Dim qdef As QueryDef
Dim selectParas As String
' UPDATE JOIN QUERY
Set qdef = CurrentDb.QueryDefs("mySavedJoinUpdateQuery")
qdef!JobNumberParam = Text31
qdef!Text33Param = Text33
qdef!Text35Param = Text35
qdef!Text37Param = Text37
qdef.Execute dbFailOnError
Set qdef = Nothing
' UPDATE SIMPLE QUERY
Set qdef = CurrentDb.QueryDefs("mySavedSimpleUpdateQuery")
qdef!JobNumberParam = Text31
qdef.Execute dbFailOnError
Set qdef = Nothing
' REQUERY LIST BOXES
listRemoveJobs.Requery
listChangeJobArea.Requery
End Sub

save result mysql query to variable in VB net

i have vb such as like this :
Sub inputdata()
Try
koneksi.Open()
***sql2 = "SELECT code_cust from customer where ('nama_cust= " & Me.cbcust.Text & "')"
cmd = New MySqlCommand(sql2, koneksi)
sql3.text=cmd.ExecuteNonQuery()***
sql = "insert into hsmaster(nohs,detailhs,beamasuk,satuanhs,idcust,asal) values ('" & Me.txtnohs.Text & "',"
sql += "'" & Me.rtdetail.Text & " ',"
sql += "'" & Me.txtbm.Text & " ',"
sql += "'" & Me.txtsatuan.Text & " ',"
sql += "'" & sql3 & " ',"
sql += "'" & Me.Cbcountry.Text & " ')"
cmd = New MySqlCommand(sql, koneksi)
cmd.ExecuteNonQuery()
MessageBox.Show("Insert data berhasil dilakukan")
Catch ex As Exception
MessageBox.Show("Insert data Gagal dilakukan")
Finally
koneksi.Close()
End Try
So i want save result of quert sql3 to slq3 , but the result was -1
Please advace ...
sql2 was query to customer table with clause name of customer was loading from combo box customer.
cbcust.text was from combo box loading data from table customer.
thanks for any kind help and sugestion.
ExecuteNonQuery is only for inserts/updates/deletes, queries that you aren't expecting to retrieve data back from. The -1 you are seeing is what databases return when executing a non-query to indicate whether the command was successful. You are correct to use ExecuteNonQuery on your second insert, but for your first select query if you want a value returned, you have to use
sql3.text = cmd.ExecuteScalar
or use a datareader
Dim dr As MySqlDataReader
dr = cmd.ExecuteReader
'check to make sure dr isnot nothing and read it, then
Dim returnValue as string = dr(code_cust)
ExecuteScalar is used for returning a single value and would probably work best in your case, datareader is used when expecting multiple columns and/or rows
You should be using parameters in your query too, but if using quotes like you are then:
***sql2 = "SELECT code_cust from customer where ('nama_cust= " & Me.cbcust.Text & "')"
needs the single quote moved like this:
***sql2 = "SELECT code_cust from customer where (nama_cust= '" & Me.cbcust.Text & "')"
because right now, that's a syntax error

Access VBA getting DateDiff results to work with Update SQL statement

I'm using Access 2007 by itself with no connections to SQLserver or anything for this process.
I want to take the result of a few DateDiff functions and use an Update SQL statement to put them into fields on a table. My table's fields are number fields, and I am under the impression that DateDiff returns a number.
I try this, but I get a data type mismatch error on the first DateDiff (Pause1). I tried taking the quotes off of the fields but then I get a different error (can't find the field '|' referred to in your expression).
Here is my code. It really starts at the comment TIME REPORTING CODE HERE:
Private Sub StopNextButton_Click()
'
GetID = Forms!frm_MainMenu!AssocIDBox
CurRecord = Forms!frm_EC_L1_L2![L#].Value
'
DoCmd.RunSQL "UPDATE tbl_Data SET tbl_Data.[tsEndAll] = Now WHERE tbl_Data.[L#] = " & CurRecord & " AND (tbl_Data.[ECName] Like 'L1*' OR tbl_Data.[ECName] Like 'L2*') "
'
'TIME REPORTING CODE HERE'
'
Pause1 = DateDiff("s", "[tsPause1]", "[tsResume1]")
Pause2 = DateDiff("s", "[tsPause2]", "[tsResume2]")
ECTime = (DateDiff("s", "[tsECStart]", "[tsUpdated]") - (Pause1 + Pause2))
LTime = DateDiff("s", "[tsStartAll]", "[tsEndAll]")
'
DoCmd.RunSQL "UPDATE tbl_Data SET [ECTime] = " & ECTime & ", [LoanTime] = " & LTime & " WHERE tbl_Data.[L#] = " & CurRecord & " AND (tbl_Data.[ECName] Like 'L1*' OR tbl_Data.[ECName] Like 'L2*') "
'
'END OF TIME REPORTING CODE'
'
DoCmd.GoToRecord , , acNext
'
ETC.
Based off of your comment I assume that those fields are on the record your form is currently 'viewing'. If so you can just refer to them as Me.tsPause1 without [] or quotes. Pretty sure you can also do just tsPause1 but I find Me.tsPause1 makes it more obvious what you are doing.
However I think you are updating the field you are currently viewing and then immediately trying to access those updated fields. I am fairly certain you will need to a Me.Refresh before those fields' new values are accessible. Hopefully someone with more specific experience will correct me if I am wrong. I think something like this should work for you:
Me.Refresh
Pause1 = DateDiff("s", Me.tsPause1, Me.tsResume1)
Pause2 = DateDiff("s", Me.tsPause2, Me.tsResume2)
ECTime = (DateDiff("s", Me.tsECStart, Me.tsUpdated) - (Pause1 + Pause2))
LTime = DateDiff("s", Me.tsStartAll, Me.tsEndAll)

Building a DCount/SQL statement in VBA via concetenation if test is true

I have a data entry form (Access 2007) which is designed to find out if the captured animal already has an existing WHno. Unfortunately, the data is messy and these is not a single unique identifier so several tests must be performed to narrow the search.
The animal could have 1 to 10 different pieces of information which will help identify the animal’s existence in the database. (The script only tests for about half of them thus far) I was thinking the best way to do this would to be to “build” a DCount and/or SQL statement based on which fields the user selects. I hope test to see if a particular text field box (unbound) has been filled out, and if yes, concatenate that section of code to the DCount/SQL statement, then move on to the next text field box to test.
Once the statement has been completely built, I want to test to see how many records have been counted/selected. If one record has been selected, I want to display the results in FormA. If 2 or more records are found, I want to display the records in a multi-listing form (FormB) from which the user can select the correct animal based on additional information not tested but displayed in FormB. If zero records are found, I want to create a new record with the data entered into the form updated into the table.
The hurdle I am struggling with now is building the DCount statements. I keep getting syntax errors . I do not know how to put this together piecemeal when the function bombs out because the syntax is incomplete (which it will be until I finish “building” it.)
I know the data is a mess. The scene out in the field is chaotic, different people gather different kinds of information, and not all the data that should be entered on the paper forms get filled out completely - if at all. The data gathering procedures are unlikely to change anytime soon.
Ideas? A different but easier approach idea is also welcome. New to this and not sure of all my programming options.
Also, how long can this statement be before it bombs out?
Code so far:
Private Sub GenerateWHno_Click()
Dim rs As DAO.Recordset
If IsNull(Forms!F_HotelEntry!txtSpecies) Or (Forms!F_HotelEntry!txtSpecies) = "" Then
MsgBox "Species is a required field. Please enter a species"
Exit Sub
End If
MsgBox txtSpecies
' Each line of code below indicates a data entry field(s) that needs testing and appended to SpeciesCount if "true". The first line is unchanging and is declared upfront.
'SpeciesCount = DCount("[Species]", "AnimalInfo", "(nz([Status])= '' OR [Status] = 'Alive' OR [Status] = 'Unknown') AND ([Species]= '" & txtSpecies & "')" _
' & "AND (((nz([L_ET_Color1])= '" & Nz(txtL_ET_Color1) & "' AND nz([L_ET_No1])= '" & nz(txtL_ET_No1) & "')" _
' & "AND (((nz([R_ET_Color1])= '" & Nz(txtR_ET_Color1) & "' AND nz([R_ET_No1])= '" & nz(txtR_ET_No1) & "')" _
' & "AND nz([L_ET_No2])= '" & nz(txtL_ET_No2) & "')" _
' & "AND nz([R_ET_No2])= '" & nz(txtR_ET_No2) & "')" _
' & "")
'If txtL_ET_Color Is Not Null Or txtL_ET_No Is Not Null Then
'LET1 = & "AND (((nz([L_ET_Color1])= '" & Nz(txtL_ET_Color1) & "' AND nz([L_ET_No1])= '" & nz(txtL_ET_No1) & "')" _
'Species Count = SpeciesCount & LET1
'End If
'If txtR_ET_Color Is Not Null Or txtR_ET_No Is Not Null Then
'RET1 = & "AND (((nz([R_ET_Color1])= '" & Nz(txtR_ET_Color1) & "' AND nz([R_ET_No1])= '" & nz(txtR_ET_No1) & "')" _
'Species Count = SpeciesCount & RET1
'End If
'If txtL_ET_No2 Is Not Null Then
'LET2 = AND nz([L_ET_No2])= '" & nz(txtL_ET_No2) & "')" _
'Species Count = SpeciesCount & LET2
'End If
'If txtR_ET_No2 Is Not Null Then
'RET2 = AND nz([R_ET_No2])= '" & nz(txtR_ET_No2) & "')" _
'Species Count = SpeciesCount & RET2
'End If
'There are about 4 more options/fields to add to the script but you get the idea.
'Thus: If user selected Species, and filled out L_ET_Color1 and/or L_ET_No1, the final concatenation (DCount statement)would look like this:
SpeciesCount = DCount("[Species]", "AnimalInfo", "([Status]= 'Alive' OR [Status] = 'Unknown' OR nz([Status]) = '') AND [Species]= '" & txtSpecies & "' AND (nz([L_ET_Color1])= '" & Nz(txtL_ET_Color1) & "' AND nz([L_ET_No1])= '" & Nz(txtL_ET_No1) & "')")
If SpeciesCount > 1 Then
MsgBox SpeciesCount & " Greater than 1. Please select correct animal"
'Create SQL statement that mimics DCount statement and display all fields from AnimalInfo table as multilisting to select from
ElseIf SpeciesCount = 0 Then
MsgBox "You need a new WHno"
WHno = Nz(DMax("WHno", "AnimalInfo")) + 1
MsgBox WHno
Set rs = CurrentDb.OpenRecordset("AnimalInfo")
rs.AddNew
rs!WHno = WHno
rs!Species = txtSpecies
rs!L_ET_Color1 = txtL_ET_Color1
rs!L_ET_No1 = txtL_ET_No1
rs.Update
rs.Close
Else
'Create SQL statement that mimics DCount statement and display all fields from AnimalInfo table as single listing in a form.
MsgBox "You're WHno is " & WHno & " Is this the correct WHno?"
End If
Forms!F_HotelEntry!txtSpecies = ""
Forms!F_HotelEntry!txtL_ET_Color1 = ""
Forms!F_HotelEntry!txtL_ET_No1 = ""
End Sub
I would suggest to first compose the condition into a string variable. There you can print its content via Debug.Print and see what the problem might be.
If you cannot spot the problem via inspection alone, paste the generated string to the Sql view of a proper query and see if Access gives you helpful information on switching to design view.

ASP issue in retrieving datas

set rs6= objconn.execute("select TotalDays from newbank where " & _
"newbank.empid= '" & session("EmpID") & "' and newbank.LeaveType = 23")
Here 23 is the value in the Field named LeaveType, but TotalDays are not being retrieved. Can you help to solve this?
Thank You
save sql and variables to a string first
EmpID = session("EmpID")
sql = "select TotalDays from newbank where empid= '" & EmpID & "' and LeaveType = 23"
log(EmpID )
log(sql)
Must EmpID be a string ?
log is your debugging or logging routine you unbdoubtly have..
session and request variables are best placed in a stringvariable first so you're sure of the type and can inspect the contents
like suggested above test the contents op the sql var againt your database, if it works there perhaps something is wrong with your connectionsetup