how to select multiple values in mysql database having multiple conditions - mysql

this is my sample form, what i wanted to happen is that anything i wrote in any field there, when i click search it will filter all the data. For example, when i search for the posted date of "2015/11/26" and having the description of "UNIT" all the details will be shown in the table, but as you can see, even the "2015/11/27" details are also shown because it has a description of "UNIT". I know that the reason is because i was using OR as the operator, but if I use AND, it displays nothing because the other text box like PO number, etc. is empty.
can someone help me please?
thanks in advance!
this is my query sample query
SELECT * FROM tbl_somonitoring
where post_date ='" & posteddate.Text & "'
or po_num ='" & ponumber.Text & "'
or doc_num='" & docnumber.Text & "'
or so_num='" & TextBox1.Text & "'
or tagging='" & tagging.Text & "'
or accnt_name='" & accntname.Text & "'
or address='" & address.Text & "'
or description='" & description.Text & "'
or model_name='" & modelname.Text & "'
or request_qty='" & requestqty.Text & "'
or color='" & color.Text & "'
or amount='" & amount.Text & "'

Maybe you can try this.
Dim commandString as String
if postdate.Text <> Nothing or ponumber.Text <> Nothing or docnumber.Text <> Nothing or TextBox1.Text <> Nothing or tagging.Text <> Nothing or accntname.Text <> Nothing or address.Text <> Nothing or description.Text <> Nothing or modelname.Text <> Nothing or requestqty.Text <> Nothing or colAND.Text <> Nothing or amount.Text <> Nothing Then
cmdstring = cmdstring & "Where "
Dim FirstState as Integer = 0
If postdate.text <> Nothing Then
cmdstring = cmdstring & "post_date = " & posteddate.Text
FirstState+=1
End If
If ponumber.Text <> Nothing Then
If FirstState > 0 Then cmdstring = cmdstring & " AND "
cmdstring = cmdstring & "po_num = " & ponumber.Text
FirstState+=1
End If
If docnumber.Text <> Nothing Then
If FirstState > 0 Then cmdstring = cmdstring & " AND "
cmdstring = cmdstring & "doc_num = " & docnumber.Text
FirstState+=1
End If
If TextBox1.Text <> Nothing Then
If FirstState > 0 Then cmdstring = cmdstring & " AND "
cmdstring = cmdstring & " so_num = " & TextBox1.Text
FirstState+=1
End If
If tagging.Text <> Nothing Then
If FirstState > 0 Then cmdstring = cmdstring & " AND "
cmdstring = cmdstring & " tagging = " & tagging.Text
End If
If accntname.Text <> Nothing Then
If FirstState > 0 Then cmdstring = cmdstring & " AND "
cmdstring = cmdstring & "accnt_name = " & accntname.Text
FirstState+=1
End If
If address.Text <> Nothing Then
If FirstState > 0 Then cmdstring = cmdstring & " AND "
cmdstring = cmdstring & "address = " & address.Text
FirstState+=1
End If
If description.Text <> Nothing Then
If FirstState > 0 Then cmdstring = cmdstring & " AND "
cmdstring = cmdstring & "description = " & description.Text
FirstState+=1
End If
If modelname.Text <> Nothing Then
If FirstState > 0 Then cmdstring = cmdstring & " AND "
cmdstring = cmdstring & " model_name = " & modelname.Text
FirstState+=1
End If
If requestqty.Text <> Nothing Then
If FirstState > 0 Then cmdstring = cmdstring & " AND "
cmdstring = cmdstring & "request_qty = " & requestqty.Text
FirstState+=1
End If
If colAND.Text <> Nothing Then
If FirstState > 0 Then cmdstring = cmdstring & " AND "
cmdstring = cmdstring & "colAND = " & colAND.Text
FirstState+=1
End If
If amount.Text <> Nothing Then
If FirstState > 0 Then cmdstring = cmdstring & " AND "
cmdstring = cmdstring & " amount = " & amount.Text
FirstState+=1
End If
End If
dim cmd as MySqlCommand = new MySqlCommand(cmdstring,con)
By that you can check each field and use the proper search query

What you need to be doing is testing like this:
(field1 = val1 or field1 = "")
And
(field2 = val2 or field2 = "")
And
...

Related

Run time keeps expanding

The code below starts with a second or less between each record and slowly increases until each record takes 15 seconds at the 500th record. Memory went from 130 Mb to 430 Mb. I have 5000 records to process so anything to speed this up would be appreciated.
[NOTE: Updating via RecordSet also expands and takes more time]
Public Sub Update_Main_Data()
Dim sql_Read As String
Dim db As DAO.Database
Dim rst_Read As DAO.Recordset, rst_Write As DAO.Recordset
Dim New_CMID As Integer, New_Lead As Integer, New_GI As Integer, New_PMO As Integer
Dim New_Dist As Integer, New_Phase As Integer, New_Type As Integer, New_Finance As Integer
DoCmd.SetWarnings False
Qoute_Char = Chr(34)
Last_Number = Qoute_Char & "AF00379-001" & Qoute_Char
sql_Read = ""
sql_Read = sql_Read & "Select ID, Contract_Number, Project_Type, Old_Type, CM, Old_CM, "
sql_Read = sql_Read & "Contract_Lead, Old_Lead, GI_PM, Old_GI, MPO_PM, Old_MPO, "
sql_Read = sql_Read & "Distrib_Contact, Old_Dist, FinanceReplacementCPUC, Old_Finance, "
sql_Read = sql_Read & "Contract_Phase, Old_Phase from [tblTrue-UpMain1] "
sql_Read = sql_Read & "WHERE Contract_Number > " & Last_Number & " ORDER BY Contract_Number"
Set db = CurrentDb
Set rst_Read = db.OpenRecordset(sql_Read)
RecNum = 0
rst_Read.MoveFirst
Do Until rst_Read.EOF
Starting_Time = Now()
Time_Start = Timer()
RecNum = RecNum + 1
If IsNull(rst_Read!Old_CM) Then
New_CMID = 0
Else
New_CMID = Nz(DLookup("CMID", "tblContractManagers1", "Old_ID = " & rst_Read!Old_CM), 0)
End If
If IsNull(rst_Read!Old_Lead) Then
New_Lead = 0
Else
New_Lead = Nz(DLookup("CMID", "tblContractManagers1", "Old_ID = " & rst_Read!Old_Lead), 0)
End If
If IsNull(rst_Read!Old_GI) Then
New_GI = 0
Else
New_GI = Nz(DLookup("ID", "tblGI-PM1", "Old_ID = " & rst_Read!Old_GI), 0)
End If
If IsNull(rst_Read!Old_MPO) Then
New_MPO = 0
Else
New_MPO = Nz(DLookup("ID", "tblPMO-PM1", "Old_ID = " & rst_Read!Old_MPO), 0)
End If
If IsNull(rst_Read!Old_Dist) Then
New_Dist = 0
Else
New_Dist = Nz(DLookup("ID", "tblDistContact1", "Old_ID = " & rst_Read!Old_Dist), 0)
End If
If IsNull(rst_Read!Old_Phase) Then
New_Phase = 0
Else
New_Phase = Nz(DLookup("ID", "tblContract_Phase1", "PhaseID = " & rst_Read!Old_Phase), 0)
End If
If IsNull(rst_Read!Old_Type) Then
New_Type = 0
Else
New_Type = Nz(DLookup("ID", "tblContract_Types1", "Old_ID = " & rst_Read!Old_Type), 0)
End If
If IsNull(rst_Read!Old_Finance) Then
New_Finance = 0
Else
New_Finance = Nz(DLookup("ID", "tblFinanceReplacement1", "Old_ID = " & rst_Read!Old_Finance), 0)
End If
Main_String = ""
Main_String = Main_String & "UPDATE [tblTrue-UpMain1] SET [tblTrue-UpMain1].CM = " & New_CMID
Main_String = Main_String & ", [tblTrue-UpMain1].Contract_Lead = " & New_Lead & ", [tblTrue-UpMain1].GI_PM = " & New_GI
Main_String = Main_String & ", [tblTrue-UpMain1].MPO_PM = " & New_PMO & ", [tblTrue-UpMain1].Distrib_Contact = " & New_Dist
Main_String = Main_String & ", [tblTrue-UpMain1].Contract_Phase = " & New_Phase & ", [tblTrue-UpMain1].Project_Type = " & New_Type
Main_String = Main_String & ", [tblTrue-UpMain1].FinanceReplacementCPUC = " & New_Finance
Main_String = Main_String & " WHERE ((([tblTrue-UpMain1].ID)=" & rst_Read!ID & "));"
DoCmd.RunSQL Main_String
Ending_Time = Now()
Time_End = Timer()
Curr_Num = Qoute_Char & rst_Read!Contract_Number & Qoute_Char
Time_String = ""
Time_String = Time_String & "INSERT INTO Contract_Time1 ( Contract_Number, "
Time_String = Time_String & "End_Time, Start_Time, Elasped_Time )"
Time_String = Time_String & "SELECT " & Curr_Num & " as New_Num, #" & Ending_Time
Time_String = Time_String & "# As New_End , #" & Starting_Time & #" as New_Start, "
Time_String = Time_String & Time_End - Time_Start & " as new_Time"
DoCmd.RunSQL Time_String
rst_Read.MoveNext
Loop
End Sub

Format DateTime to DateTime with Milliseconds

I am pulling data from database into a recordset then converting to array and then writing to a CSV.
In the database all date values are stored as timestamps in this format.
2016-05-04 08:00:00.000000
But when I write to the CSV file the timestamp does not include the milliseconds.
Anyone know how to preserve the milliseconds?
Does the data in the recordset include the milliseconds?
On Error Resume Next
Dim sPassword
Dim sUserID
Dim sDefaultLib
Dim sSystem
Dim cs
Dim rc
Dim objIEDebugWindow
sDefaultLib = *library*
sUserID = *userid*
sPassword = *password*
sSystem = *system*
cs = *connectionString*
Set con = CreateObject("ADODB.Connection")
Set data = CreateObject("ADODB.Recordset")
con.Open cs, sUserID, sPassword
rc = con.State
If (rc = 1) Then
strQuery = "SELECT * FROM Library.Table FETCH FIRST 15 ROWS ONLY FOR READ ONLY WITH UR"
data.CursorLocation = adUseClient
data.Open strQuery, con
Set filsSysObj = CreateObject("Scripting.FileSystemObject")
Dim theYear
Dim theMonth
Dim theDay
Dim mDate
mDate = Date()
theYear = DatePart("yyyy", mDate)
theMonth = Right(String(2, "0") & DatePart("m", mDate), 2)
theDate = Right(String(2, "0") & DatePart("d", mDate), 2)
mDate = theYear & theMonth & theDate
Set csvFile = filsSysObj.OpenTextFile("C:\SampleFile_" & mDate & ".csv", 8, True)
columnCount = data.Fields.Count
Set i = 0
For Each field In data.Fields
i= i + 1
If (i <> columnCount) Then
csvFile.Write Chr(34) & field.Name & Chr(34) & ","
Else
csvFile.Write Chr(34) & field.Name & Chr(34)
End If
Next
csvFile.Write vbNewLine
End If
rowCount = data.RecordCount
row = 0
Dim row
Dim column
Dim resultsArray
Dim dateArray
resultsArray = data.GetRows
debug "hi"
i = 0
Do Until i>5
MsgBox(i)
i = i + 1
'debug "in"
'Dim value
'Dim dArray()
'debug "in"
'value = Chr(34) & CStr(data.Fields(17).Value) & Chr(34) & ","
'dArray = additem(dArray, value)
'data.MoveNext
'dateArray = dArray
Loop
debug "out"
For row = 0 To UBound(resultsArray, 2)
For column = 0 To UBound(resultsArray, 1)
If row = UBound(resultsArray, 2) And column = UBound(resultsArray, 1) Then
csvFile.Write Chr(34) & resultsArray(column, row) & Chr(34)
Else
If column = 0 Then
csvFile.Write Chr(34) & formatDate(resultsArray(column, row)) & Chr(34) & ","
ElseIf column = 19 Then
csvFile.Write Chr(34) & FormatDateTime(resultsArray(column, row),4) & Chr(34) & ","
ElseIf column = 18 Then
csvFile.Write Chr(34) & formatDate(resultsArray(column, row)) & Chr(34) & ","
'ElseIf column = 17 Then
'csvFile.Write Chr(34) & formatDate(resultsArray(column, row)) & Chr(34) & ","
Else
csvFile.Write Chr(34) & resultsArray(column, row) & Chr(34) & ","
End If
End If
Next
csvFile.Write vbNewLine
Next
csvFile.close
'----------------------Helper Functions are below-----------------------------
Sub Debug(myText)
'Dim objIEDebugWindow must be defined globally
'Call like this "Debug variableName"
'Uncomment the next line to turn off debugging
'Exit Sub
If Not IsObject(objIEDebugWindow) Then
Set objIEDebugWindow = CreateObject("InternetExplorer.Application")
objIEDebugWindow.Navigate "about:blank"
objIEDebugWindow.Visible = True
objIEDebugWindow.ToolBar = False
objIEDebugWindow.Width = 200
objIEDebugWindow.Height = 300
objIEDebugWindow.Left = 10
objIEDebugWindow.Top = 10
Do While objIEDebugWindow.Busy
WScript.Sleep 100
Loop
objIEDebugWindow.Document.Title = "IE Debug Window"
objIEDebugWindow.Document.Body.InnerHTML = "<b>" & Now & "</b></br>"
End If
objIEDebugWindow.Document.Body.InnerHTML = objIEDebugWindow.Document.Body.InnerHTML & myText & "<br>" & vbCrLf
End Sub
Function formatDate(sDate)
Dim theYear
Dim theMonth
Dim theDay
Dim formattedDate
theYear = Year(sDate)
theMonth = Right(String(2,"0") & DatePart("m", sDate),2)
theDay = Right(String(2,"0") & DatePart("d", sDate),2)
formattedDate = theYear & "-" & theMonth & "-" & theDate
formatDate = formattedDate
End Function
The only field I am having issues with is field 17 of the recordset.
It is a timestamp datatype from a DB2 database.
The issue was the format is a timestamp in DB2 database. When i pull into a recordset it loses the milliseconds. My solution was to modify the query to add an extra row that pulls in only milliseconds and then later concatenate that back to the date. Please see below. Thanks for everyones help.
if(rc = 1) then
logFile.write FormatDateTime(Now(), 3) & ": Database connection successful" & vbNewLine
logFile.write FormatDateTime(Now(), 3) &": Default Library: " & sDefaultLib & vbNewLine
logFile.write FormatDateTime(Now(), 3) & ": Signed into server as: " & sUserID & vbNewLine
logFile.write FormatDateTime(Now(), 3) & ": System: " & sSystem & vbNewLine
strQuery = "SELECT ws_date, groupcd, userid, firstname, lastname, clientcd, unitcd, categorycd, category, activity, wrktype, subwrktype, step_begin, step_end, report_indicator, report_indicator, count, event_dattim, key_date, key_time, key_milsec, microsecond(event_dattim) FROM *Library.Name* FOR READ ONLY WITH UR"
data.CursorLocation = adUseClient
data.open strQuery, con
if data.EOF then
logFile.write FormatDateTime(Now(), 3) & ": The query returned no data"
logFile.write FormatDateTime(Now(), 3) & ": ---------------- The script DailyWorkstepReport.vbs file was abended at " & Now() &". There was no worksteps file created. ----------------" & vbNewLine
logFile.close
end if
columnCount = data.Fields.Count
columnCount = columnCount - 1
Set filsSysObj = CreateObject("Scripting.FileSystemObject")
Set csvFile = filsSysObj.OpenTextFile("C:\VBScript\Dailys\" & fname, 8, True)
set i = 0
for each field in data.Fields
i= i + 1
if i < columnCount then
csvFile.Write chr(34) & field.name & chr(34) & ","
elseif i = columnCount then
csvFile.Write chr(34) & field.name & chr(34)
else
exit for
end if
next
csvFile.Write vbNewLine
else
logFile.write FormatDateTime(Now(), 3) & ": Database connection was unsuccessful. Database Connection Return Code: " & rc
logFile.write FormatDateTime(Now(), 3) & ": ---------------- The script DailyWorkstepReport.vbs file was abended at " & Now() &". ----------------" & vbNewLine
logFile.close
csvfile.close
wscript.quit
end if
dim row
dim column
dim resultsArray
resultsArray = data.GetRows
dim arrayRows
arrayRows = ubound(resultsArray, 2)
if arrayRows <> 0 then
logFile.write FormatDateTime(Now(), 3) & ": " & (arrayRows + 1) & " rows were successfully read into the array for file " & fname & vbnewline
for row = 0 to UBound(resultsArray, 2)
for column = 0 to (UBound(resultsArray, 1) - 1)
if row = Ubound(resultsArray, 2) and column = (ubound(resultsArray, 1) - 1) then
csvFile.Write chr(34) & resultsArray(column, row) & chr(34)
else
if column = 0 then
csvFile.Write chr(34) & formatDate(resultsArray(column, row)) & chr(34) & ","
elseif column = 19 then
csvFile.Write chr(34) & FormatDateTime(resultsArray(column, row),4) & chr(34) & ","
elseif column = 18 then
csvFile.Write chr(34) & formatDate(resultsArray(column, row)) & chr(34) & ","
elseif column = 17 then
Dim fDate
fDate = formatDate(resultsArray(column, row)) & " " & FormatDateTime(resultsArray(column, row),4) & ":" & second(resultsArray(column,row)) & "." & resultsArray((ubound(resultsArray, 1)), row)
csvFile.Write chr(34) & fDate & chr(34) & ","
else
csvFile.Write chr(34) & resultsArray(column, row) & chr(34) & ","
end if
end if
next
csvFile.Write vbNewLine
next
logfile.write FormatDateTime(Now(), 3) & ": " & (row) & " rows have been written to " & fname &vbNewLine
else
logFile.write FormatDateTime(Now(), 3) & ": There was no data in the query results array for file " & fname & vbNewLine
logFile.write FormatDateTime(Now(), 3) & ": ---------------- The script DailyWorkstepReport.vbs file was abended at " & Now() &". ----------------" & vbNewLine
logfile.close
csvfile.close
wscript.quit
end if
csvFile.close
logfile.write "---------------- DailyWorkstepReport.vbs script successfully ended at " & Now() & "----------------" & vbNewLine
logfile.close
wscript.quit
REM ----------------------Helper Functions are below-----------------------------
Sub Debug( myText )
'Dim objIEDebugWindow must be defined globally
'Call like this "Debug variableName"
'Uncomment the next line to turn off debugging
'Exit Sub
If Not IsObject( objIEDebugWindow ) Then
Set objIEDebugWindow = CreateObject( "InternetExplorer.Application" )
objIEDebugWindow.Navigate "about:blank"
objIEDebugWindow.Visible = True
objIEDebugWindow.ToolBar = False
objIEDebugWindow.Width = 200
objIEDebugWindow.Height = 300
objIEDebugWindow.Left = 10
objIEDebugWindow.Top = 10
Do While objIEDebugWindow.Busy
WScript.Sleep 100
Loop
objIEDebugWindow.Document.Title = "IE Debug Window"
objIEDebugWindow.Document.Body.InnerHTML = "<b>" & Now & "</b></br>"
End If
objIEDebugWindow.Document.Body.InnerHTML = objIEDebugWindow.Document.Body.InnerHTML & myText & "<br>" & vbCrLf
End Sub
function formatDate(sDate)
Dim theYear
Dim theMonth
Dim theDay
Dim formattedDate
theYear = Year(sDate)
theMonth = Right(String(2,"0") & DatePart("m", sDate),2)
theDay = Right(String(2,"0") & DatePart("d", sDate),2)
formattedDate = theYear & "-" & theMonth & "-" & theDate
formatDate = formattedDate
end function

Millisecond time: Filter form by date

I am trying to implement millisecond timestamping in Access 2010/13 using this method;
MS Access Can Handle Millisecond Time Values--Really - See more at:
The Millisecond value is queried by;
SELECT DateValueMsec([DateTimeMs]) AS DateOnly FROM - to provide a date only control to sort the form from a textbox.
Any filter applied programmatically on DateOnly yeilds 0 results.
Private Sub BuildFilter()
Dim strFilter As String
Dim ctl As Control
strFilter = ""
'add selected values to string
For Each ctl In Me.FormHeader.Controls
With ctl
If .ControlType = acTextBox Or .ControlType = acComboBox Then
If Nz(.Value) <> "" Then
If InStr(.Name, "Date") <> 0 Then
If Nz(StartDate) <> "" And Nz(EndDate) <> "" And InStr(strFilter, "DateOnly") = 0 Then
strFilter = strFilter & "[DateOnly] BETWEEN #" & Me.StartDate.Value & "# AND #" & Me.EndDate.Value & "# AND "
ElseIf Nz(StartDate) <> "" And InStr(strFilter, "DateOnly") = 0 Then
strFilter = strFilter & "[DateOnly] >= #" & DateValueMsec(Me.StartDate.Value) & "# AND "
' strFilter = strFilter & "[DateOnly] >= #" & Me.StartDate.Value & "# AND "
ElseIf Nz(EndDate) <> "" And InStr(strFilter, "DateOnly") = 0 Then
strFilter = strFilter & "[DateOnly] <= #" & Me.EndDate.Value & "# AND "
End If
ElseIf InStr(.Name, "ID") <> 0 Then
strFilter = strFilter & "[" & .Name & "] = " & .Value & " AND "
Else
strFilter = strFilter & "[" & .Name & "] = '" & .Value & "' AND "
End If
End If
End If
End With
Next ctl
'trim trailing
strFilter = TrimR(strFilter, 5)
Debug.Print strFilter
With Me.subfrmzzAuditTrailDisplay
.Form.Filter = strFilter
.Form.FilterOn = True
End With
End Sub
Answer! From #pathDongle
Time is stored as Millisecond UTC;
!DateTimeMS = GetTimeUTC()
And restored by;
Public Function UTCtoTimeLocal(dSysUTC As Date) As Date
'Dim sysTime As SYSTEMTIME
Dim DST As Long
Dim tzi As TIME_ZONE_INFORMATION
DST = GetTimeZoneInformation(tzi)
UTCtoTimeLocal = dSysUTC - TimeSerial(0, tzi.Bias, 0) + IIf(DST = 2, TimeSerial(1, 0, 0), 0)
End Function
Query;
SELECT tblzzAuditTrail.DateTimeMS, FormatDate(UTCtoTimeLocal([DateTimeMS])) AS DateTimeLocal
Which can be filtered on as a String.
Private Sub BuildFilter()
Dim strFilter As String
Dim ctl As Control
strFilter = ""
'add selected values to string
For Each ctl In Me.FormHeader.Controls
With ctl
If .ControlType = acTextBox Or .ControlType = acComboBox Then
If Nz(.Value) <> "" Then
If InStr(.Name, "Date") <> 0 Then
If Nz(StartDate) <> "" And Nz(EndDate) <> "" And InStr(strFilter, "DateTimeLocal") = 0 Then
strFilter = strFilter & "[DateTimeLocal] BETWEEN '" & FormatDate(Me.StartDate.Value) & "' AND '" & FormatDate(Me.EndDate.Value) & "' AND "
ElseIf Nz(StartDate) <> "" And InStr(strFilter, "DateTimeLocal") = 0 Then
strFilter = strFilter & "[DateTimeLocal] > '" & FormatDate(Me.StartDate.Value) & "' AND "
ElseIf Nz(EndDate) <> "" And InStr(strFilter, "DateTimeLocal") = 0 Then
strFilter = strFilter & "[DateTimeLocal] <= '" & FormatDate(Me.EndDate.Value) & "' AND "
End If
ElseIf InStr(.Name, "ID") <> 0 Then
strFilter = strFilter & "[" & .Name & "] = " & .Value & " AND "
Else
strFilter = strFilter & "[" & .Name & "] = '" & .Value & "' AND "
End If
End If
End If
End With
Next ctl
'trim trailing And
strFilter = TrimR(strFilter, 5)
Debug.Print strFilter
With Me.subfrmzzAuditTrailDisplay
.Form.Filter = strFilter
.Form.FilterOn = True
End With
End Sub
Resulting Filter String;
[UserID] = 2 AND [DateTimeLocal] BETWEEN '06/01/2015 00:00:00.000' AND '07/01/2015 00:00:00.000'
As per my other question;
millisecond-time-msec2-incorrect-return

Vb.net and MySQL issue

When I click on save, I get the message:
You have an error in your SQL syntax;Check the manual that corresponds to your mySQL Server version for the right Syntax to use near 'idDrug=21' at line 21
Here is my code:
Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
Dim i As Integer
Dim xid As Integer
Dim xQTY(0) As Integer
Dim xQTY_ID(0) As Integer
Dim xCount As Integer
Dim xCounter_ID(0) As Integer
'Dim sqlstrx(5) As String
xid = 0
If lstitems.Items.Count > 0 Then
If Split(Me.Text, " - ")(1) = "Add" Then
sqlSTR = "INSERT INTO orders (CustID, Cust_Name, order_date) " & _
"VALUES (" & txtcustid.Text & ", " _
& "'" & txtcustname.Text & "', " _
& "'" & Format(dttoday.Value, "yyyy-MM-dd") & "')"
ExecuteSQLQuery(sqlSTR)
sqlSTR = "SELECT * FROM orders ORDER BY order_no DESC"
ExecuteSQLQuery(sqlSTR)
xid = sqlDT.Rows(0)("order_no")
For i = 0 To lstitems.Items.Count - 1
sqlSTR = "INSERT INTO orders_detail (order_no, idDrug, DrugName, Unit_Cost, qty, totalcost) " & _
"VALUES (" & xid & ", " _
& lstitems.Items(i).Text & ", " _
& "'" & lstitems.Items(i).SubItems(1).Text & "', " _
& "'" & lstitems.Items(i).SubItems(2).Text & "', " _
& lstitems.Items(i).SubItems(3).Text & ", " _
& lstitems.Items(i).SubItems(4).Text & ")"
ExecuteSQLQuery(sqlSTR)
'UPDATE STOCKS
sqlSTR = "UPDATE stockbalances SET ItemQuantity = ItemQuantity -" & CDbl(lstitems.Items(i).SubItems(3).Text) & _
"WHERE idDrug =" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
Next
Else
'delete first
For i = 0 To UBound(deleteID)
ExecuteSQLQuery("DELETE FROM Orders_detail WHERE order_no =" & txtorderno.Text & " AND idDrug =" & deleteID(i))
sqlSTR = "UPDATE stockbalances SET ItemQuantity = ItemQuantity +" & Delete_QTY(i) & _
" WHERE idDrug =" & deleteID(i)
ExecuteSQLQuery(sqlSTR)
Next
For i = 0 To UBound(deleteID)
ReDim deleteID(i)
deleteID(i) = 0
Next
del = 0
'--
'If lstitems.Items.Count > 0 Then
For i = 0 To lstitems.Items.Count - 1
'MsgBox(stockID & " " & lstitems.Items(i).Text)
sqlSTR = "SELECT * FROM orders_detail WHERE order_no =" & stockID & " AND idDrug =" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
If sqlDT.Rows.Count > 0 Then
ReDim Preserve xQTY(i), xQTY_ID(i)
xQTY(i) = sqlDT.Rows(0)("QTY")
'xQTY_ID(i) = sqlDT.Rows(0)("Item_ID")
End If
'MsgBox(sqlDT.Rows(0)("QTY"))
Next
For i = 0 To lstitems.Items.Count - 1
'MsgBox(xQTY_ID(i))
If lstitems.Items(i).Index <= (UBound(xQTY)) Then
If CDbl(lstitems.Items(i).SubItems(4).Text) < xQTY(i) Then
'MsgBox(xQTY(i) - CDbl(lstitems.Items(i).SubItems(4).Text))
If xQTY(i) > 0 Then
sqlSTR = "UPDATE orders_detail SET qty =" & lstitems.Items(i).SubItems(4).Text & ", " _
& "totalcost =" & lstitems.Items(i).SubItems(3).Text * lstitems.Items(i).SubItems(4).Text & _
" WHERE Order_no =" & stockID & " AND idDrug=" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
'UPDATE STOCKS
sqlSTR = "UPDATE stockBalances SET ItemQuantity = ItemQuantity + " & (xQTY(i) - CDbl(lstitems.Items(i).SubItems(4).Text)) & _
" WHERE idDrug =" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
End If
ElseIf CDbl(lstitems.Items(i).SubItems(4).Text) > xQTY(i) Then
If xQTY(i) > 0 Then
sqlSTR = "UPDATE orders_detail SET qty =" & lstitems.Items(i).SubItems(4).Text & ", " _
& "totalcost =" & lstitems.Items(i).SubItems(3).Text * lstitems.Items(i).SubItems(4).Text & _
" WHERE order_no =" & stockID & " AND idDrug=" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
'UPDATE STOCKS
sqlSTR = "UPDATE Stockbalances SET ItemQuantity = ItemQuantity - " & (CDbl(lstitems.Items(i).SubItems(4).Text) - xQTY(i)) & _
" WHERE idDrug =" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
End If
End If
End If
Next
' End If
'search for new item
sqlSTR = "SELECT * FROM orders_detail WHERE order_no =" & stockID & " ORDER BY Order_Dtl ASC"
ExecuteSQLQuery(sqlSTR)
xCount = sqlDT.Rows.Count
For i = 0 To sqlDT.Rows.Count - 1
ReDim Preserve xCounter_ID(i)
xCounter_ID(i) = sqlDT.Rows(i)("idDrug")
' xCount = i + 1
Next
'check
If lstitems.Items.Count > xCount Then
For i = 0 To lstitems.Items.Count - 1
If i > UBound(xCounter_ID) Then
'MsgBox(lstitems.Items(i).Text)
sqlSTR = "INSERT INTO orders_detail (order_no, idDrug, DrugName, price, qty, totalcost) " & _
"VALUES (" & txtorderno.Text & ", " _
& lstitems.Items(i).Text & ", " _
& "'" & lstitems.Items(i).SubItems(0).Text & "', " _
& "'" & lstitems.Items(i).SubItems(1).Text & "', " _
& lstitems.Items(i).SubItems(2).Text & ", " _
& lstitems.Items(i).SubItems(3).Text & ", " _
& lstitems.Items(i).SubItems(4).Text & ")"
ExecuteSQLQuery(sqlSTR)
'UPDATE STOCKS
sqlSTR = "UPDATE stockbalances SET ItemQuantity = ItemQuantity -" & CDbl(lstitems.Items(i).SubItems(4).Text) & _
"WHERE idDrug =" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
End If
Next
End If
End If
Else
MsgBox("Can't save without details !!", MsgBoxStyle.Exclamation, xTitlename)
Exit Sub
End If
MsgBox("Record has been saved !!", MsgBoxStyle.Information, xTitlename)
sqlSTR = "SELECT distinct orders.order_no AS 'Order No.', Cust_Name as 'Customer Name', order_date AS 'Date', sum(totalcost) AS 'TOTAL DUE' FROM orders_detail " & _
"INNER JOIN orders ON orders_detail.order_no = orders.order_no " & _
"WHERE order_date ='" & Format(dttoday.Value, "yyyy-MM-dd") & "' GROUP BY orders.order_no, Cust_Name, order_date"
FillListView(ExecuteSQLQuery(sqlSTR), FrmORDERLIST.lstorder, 0)
Me.Close()
End Sub
It is impossible to fix all of your code and to be precise what is the exact cause of your error.
Suffice to say that you never should do a database application using that kind of string concatenation approach. Any of your text fields could cause the error because it contains single quotes or any of your date items could cause the error because it is not formatted how the database requires. (Same for decimals and other floating point values).
To solve this problems (and to avoid the dangerous Sql Injection scenarion) exists the parameterized queries approach.
So, just an example on what you need to do for every line of your sql commands
sqlSTR = "INSERT INTO orders_detail (order_no, idDrug, DrugName, " & _
"Unit_Cost, qty, totalcost) VALUES (" & _
"#id, #iddrug, #dname,#unit, #qty, #total)"
Using cmd = new MySqlCommand(sqlStr, connection)
cmd.Parameters.AddWithValue("#id", xid)
cmd.Parameters.AddWithValue("#idrug", Convert.ToInt32(lstitems.Items(i).Text))
cmd.Parameters.AddWithValue("#dname", lstitems.Items(i).SubItems(1).Text)
cmd.Parameters.AddWithValue("#unit", lstitems.Items(i).SubItems(2).Text)
cmd.Parameters.AddWithValue("#qty", Convert.ToDecimal(lstitems.Items(i).SubItems(3).Text ))
cmd.Parameters.AddWithValue("#total", Convert.ToDecimal(lstitems.Items(i).SubItems(4).Text))
cmd.ExecuteNonQuery()
End Using
Notice how, in a parameterized query, you could specify the datatype of the value passed for the parameter using the Convert.ToXXXXX method. In this way the framework code could prepare the appropriate formatting of your values to be passed to the database engine.
Not to mention the now readable query text.

change character in all text fields

I need your help. I woulod like to change one char by another but in all database and i have several table and fields. So i'm building a function in VB but that change nothing and i have no error. I think that my condition is false but i don't see how to correct it :/
Public Sub updateField()
Dim db As DAO.Database, td As DAO.TableDef, field As DAO.field
Dim rs As DAO.Recordset, sSQL As String, sData As String
Set db = CurrentDb
Change = "\"""
replaced = """"
'each table in db
For Each tbd In db.TableDefs
'each field in table
For Each fld In tbd.Fields
'check if String Data have my character
If InStr(1, fld.Name, Change) Then
sSQL = "UPDATE " & tbd.Name & " SET " & fld.Name & " = replace([" & fld.Name & "], " & Change & ", " & replaced & ")"
db.Execute sSQL
End If
Next
Next
End Sub
EDIT :
I finally find what's wrong. if some people are interested :
Set db = CurrentDb
Change = "\"""
replaced = """"
'each table in db
For Each tbd In db.TableDefs
'each field in table
For Each fld In tbd.Fields
If Left(tbd.Name, 4) <> "MSys" And Left(tbd.Name, 4) <> "~TMP" Then
If fld.Type = dbText Or fld.Type = dbMemo Then
sSQL = "UPDATE " & tbd.Name & " SET " & fld.Name & " = replace([" & fld.Name & "],'" & Chr(92) + Chr(34) & "','" & Chr(34) & "')"
db.Execute sSQL
'Debug.Print (sSQL)
End If
End If
Next
Next
Thx for your help guys ;)
If it should help there my solution :
Public Sub updateField()
Dim db As DAO.Database, td As DAO.TableDef, field As DAO.field
Dim rs As DAO.Recordset, sSQL As String, sData As String, change As String, replace As String
change = "\'"
replace = "'"
' simple quote = 39
' doulbe quote = 34
' antislash = 92
' retour chariot = 13
' n = 110
' r = 114
Set db = CurrentDb
'each table in db
For Each tbd In db.TableDefs
'each field in table
For Each fld In tbd.Fields
If Left(tbd.Name, 4) <> "MSys" And Left(tbd.Name, 4) <> "~TMP" Then
If fld.Type = dbText Or fld.Type = dbMemo Then
' \r\n
'sSQL = "UPDATE " & tbd.Name & " SET [" & fld.Name & "] = replace([" & fld.Name & "],'\r\n','" & Chr(13) & Chr(10) & "');"
' \"
'sSQL = "UPDATE " & tbd.Name & " SET [" & fld.Name & "] = replace([" & fld.Name & "],'" & Chr(92) + Chr(34) & "','" & Chr(34) & "');"
'db.Execute sSQL
sSQL = "UPDATE " & tbd.Name & " SET [" & fld.Name & "] = replace([" & fld.Name & "],'\''','''');"
db.Execute sSQL
'Debug.Print (sSQL)
End If
End If
Next
Next
End Sub
That's works for me ;)