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.
Related
I'm having a problem about my code, i already tried to put the specified table for each column, In which part of my code was having a problem?
clientid = clientid.Substring(0, 3)
rnd = random.Next(100, 999)
clientid = clientid & "-" & Format(Now, "MMdd") & "-" & rnd
query = "SELECT COUNT(*) FROM tbl_clients WHERE clients_Record_Num ='" & clientid & "'"
sqlcmd = New MySqlCommand(query, conn)
chkclientid = sqlcmd.ExecuteScalar()
While chkclientid > 0
clientid = clientid.Substring(0, 3)
rnd = random.Next(100, 999)
clientid = clientid & "-" & Format(Now, "MMdd") & "-" & rnd
query = "SELECT COUNT(*) FROM tbl_clients WHERE clients_record_num ='" & clientid & "'"
sqlcmd = New MySqlCommand(query, conn)
chkclientid = sqlcmd.ExecuteScalar()
End While
query = "Insert into tbl_clients(clients_record_num,clients_client_id,clients_name,clients_contact_number,clients_address,clients_industry,clients_status,clients_delegate,clients_notes) values ('" & clientid.Substring(0, 3) &_ "-" & dttime & "-" & rnd &_ "','" & clientid & _
"', '" & txtClientName.Text & "','" & txtClientContactNum.Text & "','" & txtClientAddress.Text & _
"','" & cmbIndustry.Text & "', '" & cmbStatus.Text & "', '" & cmbDelegate.Text & "','" & txtNotes.Text & "','0')"
sqlCommand.Connection = conn
sqlCommand.CommandText = query
sqlCommand.ExecuteNonQuery()
As #jmcilhinney commented, change your insert query to use parameters as it will be easier to read and to ensure that the number of values matches the number of columns.
Here's some 'template' code for you to expand on:
Dim InsertCmdText As String =
"Insert into tbl_clients(clients_record_num,clients_client_id,clients_name,clients_contact_number,clients_address,clients_industry,clients_status,clients_delegate,clients_notes) " &
"values (#clients_record_num,#clients_client_id,#clients_name,#clients_contact_number,#clients_address,#clients_industry,#clients_status,#clients_delegate,#clients_notes)"
Dim SqlConnectionString As String = "Your Connection Info"
Using cmd As New SqlCommand(InsertCmdText, New SqlConnection(SqlConnectionString))
Try
cmd.Parameters.AddWithValue("#clients_record_num", "Value Needed")
cmd.Parameters.AddWithValue("#clients_client_id", "Value Needed")
cmd.Parameters.AddWithValue("#clients_name", "Value Needed")
'repeat above for all params
cmd.Connection.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
'Handle your exception
Finally
cmd.Connection.Close()
End Try
End Using
Alternatively use Parameters.Add instead of AddWithValue. For discussion on merits of each, see SqlCommand Parameters Add vs. AddWithValue
So I've got the code below (not all of it is grey for some reason)
Private Sub CmdEdit_Click()
Me.Tableinform.Requery
Dim rs As DAO.Recordset
Set rs = Me.Tableinform.Form.RecordsetClone
'get data to textbox control
With rs
If .RecordCount > 0 Then
With Me.Tableinform.Form.Recordset
Me.ShowIDbox = .Fields("[ID]").Value
Me.CompbyDD = .Fields("[Received By]")
Me.Date1 = .Fields("[Date Received]")
Me.Date2 = .Fields("[Date Processed]")
Me.ReqType = .Fields("[Request Type]")
Me.InsName = .Fields("[Insured Name]")
Me.RiskNo = .Fields("[Risk Number]")
Me.EndtRef = .Fields("[Endorsement Reference]")
Me.EOCNo = .Fields("[EOC Number]")
Me.Tech = .Fields("[Technician]")
Me.BillIns = .Fields("[Billing Instructions]")
Me.Addrecord.Caption = "Update"
Me.CmdEdit.Enabled = False
Me.cmdDuplicate.Enabled = True
Me.CmdDelete.Enabled = True
End With
End If
End With
End Sub
After one Edit and Update, the edit function throws out Error '3021' No Current Record?
Please show me where I am going wrong with this.
Add/Update button as follows:
If Me.ShowIDbox.Value = "" Then
CurrentDb.Execute "INSERT INTO fmdatatable( [Received By], [Date Received], [Date Processed], [Request Type], [Insured Name], [Risk Number], [Endorsement Reference], [EOC Number], [Technician], [Billing Instructions]) " & _
" VALUES ('" & Me.CompbyDD & "','" & Me.Date1 & "','" & Me.Date2 & "','" & Me.ReqType & "','" & Me.InsName & "','" & Me.RiskNo & "','" & Me.EndtRef & "','" & Me.EOCNo & "','" & Me.Tech & "','" & Me.BillIns & "')"
Else
CurrentDb.Execute "UPDATE fmdatatable SET [Received By]='" & Me.CompbyDD & "'" & _
", [Date Received]='" & Me.Date1 & "'" & _
", [Date Processed]='" & Me.Date2 & "'" & _
", [Request Type]='" & Me.ReqType & "'" & _
", [Insured Name]='" & Me.InsName & "'" & _
", [Risk Number]='" & Me.RiskNo & "'" & _
", [Endorsement Reference]='" & Me.EndtRef & "'" & _
", [EOC Number]='" & Me.EOCNo & "'" & _
", [Technician]='" & Me.Tech & "'" & _
", [Billing Instructions]='" & BillIns & "'" & _
" WHERE [ID]=" & Me.ShowIDbox.Value
End If
Me.CompbyDD = "-Please Select-"
Me.Date1 = ""
Me.Date2 = ""
Me.ReqType = "-Please Select-"
Me.InsName = ""
Me.RiskNo = ""
Me.EndtRef = ""
Me.EOCNo = ""
Me.Tech = ""
Me.BillIns = "-Please Select-"
Me.ShowIDbox = ""
Me.Addrecord.Caption = "Add Record"
Me.CmdEdit.Enabled = True
Me.cmdDuplicate.Enabled = False
Me.CmdDelete.Enabled = False
Tableinform.Form.Requery
This edit works once, then all subsequent later edits are throwing errors out.
I am facing a little issue now. My issue is that currently when i made edit to the current record in my subform and click on "update" it will overwrite my previous record which i do not want.
Instead, I would like to add my edited data record from the subform and insert it into the subform as a new record with the same PO number as the one that i am editing.
Below are my code:
Private Sub cmdAdd_Click()
'when we click on button Add there are two options
'1. for insert
'2. for update
If Me.txtID.Tag & "" = "" Then
'this is for insert new
'add data to table
CurrentDb.Execute "INSERT INTO mxd " & _
"(ID,Fabrication,Width,FinishedGoods,Colour, " & _
"LabDipCode,GrossWeight,NettWeight, " & _
"Lbs,Loss,Yds,Remarks,POType,ComboName,GroundColour)" & _
" VALUES(" & Me.txtID & ",'" & Me.txtFabrication & "','" & _
Me.txtWidth & "','" & Me.txtFinishedGood & "','" & _
Me.txtColour & "','" & Me.txtLabDipCode & "','" & _
Me.txtGrossweight & "','" & _ Me.txtNettweight & "','" & _
Me.txtLbs & "','" & Me.txtLoss & "','" & _ Me.txtYds & "','" & _
Me.txtRemarks & "','" & Me.cboPoType "','" & _
Me.txtGroundColour & "','" & Me.txtComboName & "')"
Else
'otherwise (Tag of txtID store the id of student to be modified)
CurrentDb.Execute "UPDATE mxd " & _
" SET ID = " & Me.txtID & _
", Fabrication = '" & Me.txtFabrication & "'" & _
", Width = '" & Me.txtWidth & "'" & _
", FinishedGoods = '" & Me.txtFinishedGood & "'" & _
", Colour = '" & Me.txtColour & "'" & _
", LabDipCode = '" & Me.txtLabDipCode & "'" & _
", GrossWeight = '" & Me.txtGrossweight & "'" & _
", NettWeight = '" & Me.txtNettweight & "'" & _
", LBS = '" & Me.txtLbs & "'" & _
", Loss = '" & Me.txtLoss & "'" & _
", Yds = '" & Me.txtYds & "'" & _
", Remarks = '" & Me.txtRemarks & "'" & _
", POType = '" & Me.cboPoType & "'" & _
", ComboName = '" & Me.txtComboName & "'" & _
", GroundColour = '" & Me.txtGroundColour & "'" & _
" WHERE ID = " & Me.txtID.Tag
End If
'clear form
cmdClear_Click
'refresh data in list on form
FormMxdSub.Form.Requery
End Sub
Private Sub cmdClear_Click()
Me.txtID = ""
Me.txtFabrication = ""
Me.txtWidth = ""
Me.txtFinishedGood = ""
Me.txtColour = ""
Me.txtLabDipCode = ""
Me.txtGrossweight = ""
Me.txtNettweight = ""
Me.txtLbs = ""
Me.txtLoss = ""
Me.txtYds = ""
Me.txtRemarks = ""
Me.cboPoType = ""
Me.txtKeywords = ""
Me.txtComboName = ""
Me.txtGroundColour = ""
'focus on ID text box
Me.txtID.SetFocus
'set button edit to enable
Me.cmdEdit.Enabled = True
'change caption of button add to Add
Me.cmdAdd.Caption = "Add"
'clear tag on txtID for reset new
Me.txtID.Tag = ""
End Sub
Private Sub cmdClose_Click()
DoCmd.Close
End Sub
Private Sub cmdDelete_Click()
'delete record
'check existing selected record
If Not (Me.FormMxdSub.Form.Recordset.EOF And
Me.FormMxdSub.Form.Recordset.BOF) Then
'confirm delete
If MsgBox("Are you sure you want to delete?", vbYesNo) = vbYes Then
'delete now
CurrentDb.Execute "DELETE FROM mxd " & _
"where ID = " & Me.FormMxdSub.Form.Recordset.Fields("ID")
'refresh data in list
Me.FormMxdSub.Form.Requery
End If
End If
End Sub
Private Sub cmdEdit_Click()
'check whether there is exists data in list
If Not (Me.FormMxdSub.Form.Recordset.EOF And
Me.FormMxdSub.Form.Recordset.BOF) Then
'get data to text box control
With Me.FormMxdSub.Form.Recordset
Me.txtID = .Fields("ID")
Me.txtFabrication = .Fields("Fabrication")
Me.txtWidth = .Fields("Width")
Me.txtFinishedGood = .Fields("FinishedGoods")
Me.txtColour = .Fields("Colour")
Me.txtLabDipCode = .Fields("LabDipCode")
Me.txtGrossweight = .Fields("GrossWeight")
Me.txtNettweight = .Fields("NettWeight")
Me.txtLbs = .Fields("Lbs")
Me.txtLoss = .Fields("Loss")
Me.txtYds = .Fields("Yds")
Me.txtRemarks = .Fields("Remarks")
Me.cboPoType = .Fields("POType")
Me.txtComboName = .Fields("ComboName")
Me.txtGroundColour = .Fields("GroundColour")
'store id of student in Tag of txtID in case id is modified
Me.txtID.Tag = .Fields("ID")
'change caption of button add to update
'Me.cmdAdd.Caption = "Update"
'disable button edit
Me.cmdEdit.Enabled = False
End With
End If
End Sub
You can use the RecordsetClone to create a dupe of the current record. Much faster and cleaner and no Tag is needed:
Private Sub btnCopy_Click()
Dim rstSource As DAO.Recordset
Dim rstInsert As DAO.Recordset
Dim fld As DAO.Field
If Me.NewRecord = True Then Exit Sub
Set rstInsert = Me.RecordsetClone
Set rstSource = rstInsert.Clone
With rstSource
If .RecordCount > 0 Then
' Go to the current record.
.Bookmark = Me.Bookmark
With rstInsert
.AddNew
For Each fld In rstSource.Fields
With fld
If .Attributes And dbAutoIncrField Then
' Skip Autonumber or GUID field.
ElseIf .Name = "SomeFieldToExclude" Then
' Leave field blank.
ElseIf .Name = "SomeOtherFieldToExclude" Then
' Leave field blank.
Else
' Copy field content.
rstInsert.Fields(.Name).Value = .Value
End If
End With
Next
.Update
' Go to the new record and sync form.
.MoveLast
Me.Bookmark = .Bookmark
.Close
End With
End If
.Close
End With
Set rstInsert = Nothing
Set rstSource = Nothing
End Sub
Of course, if you place the button on the main form, replace in the code Me with a reference to the subform: Me!NameOfYourSubformControl.Form
Private Sub btnSave_ClientOrderStatus_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave_ClientOrderStatus.Click
mysqlconn = New MySqlConnection
mysqlconn.ConnectionString = serverstring
Try
mysqlconn.Open()
Dim query As String = "insert into isad.invoice_table(Invoice, Clientnumber, Firstname, Lastname, ProductID, Name, Price, Qty, Description, Total, DateCreated) values "
command = New MySqlCommand(query, mysqlconn)
For i = 0 To ListView1.Items.Count - 1
query &= "('" & txtInvoice_ClientOrderStatus.Text & "','" & txtClientNumber_ClientOrderStatus.Text.Replace("'", "\'") & "','" & txtFname_ClientOrderStatus.Text.Replace("'", "\'") & _
"', '" & txtLname_ClientOrderStatus.Text.Replace("'", "\'") & "', #ProductID" & i.ToString & ", #Name" & i.ToString & ", #Price" & i.ToString & _
", #Quantity" & i.ToString & ", #Description" & i.ToString & ", '" & txtTotal_ClientOrderStatus.Text & "',now())"
command.Parameters.AddWithValue("#ProductID" & i.ToString, ListView1.Items(i).Text)
command.Parameters.AddWithValue("#Name" & i.ToString, ListView1.Items(i).SubItems(1).Text)
command.Parameters.AddWithValue("#Price" & i.ToString, ListView1.Items(i).SubItems(2).Text)
command.Parameters.AddWithValue("#Quantity" & i.ToString, ListView1.Items(i).SubItems(3).Text)
command.Parameters.AddWithValue("#Description" & i.ToString, ListView1.Items(i).SubItems(4).Text)
query &= ", "
Next
query = query.Substring(0, query.Length - 2)
READER = command.ExecuteReader
SBP2.Text = "Status : Client invoice has been created"
MsgBox("Saving Client Order Succeed", vbInformation, "Done")
mysqlconn.Close()
autoincrement_ClientOrderStatus()
cleartext_ClientOrderStatus()
btnSave_ClientOrderStatus.Enabled = False
btnAdd_ClientOrderStatus.Text = "Add Transaction"
READER.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
mysqlconn.Close()
Finally
mysqlconn.Dispose()
End Try
End Sub
heres my project image, maybe it can help you genospos
Here's the error when i click save
If you want to use a single access to DB you need to write a code for looping all rows to compose the query string:
This should work for you
Dim query As String = "insert into isad.invoice_table(Invoice, Clientnumber, Firstname, Lastname, ProductID, Name, Price, Qty, Description, Total, DateCreated) values "
Command = New MySqlCommand(query, mysqlconn)
For i = 0 To ListView1.Items.Count - 1
query &= "('" & txtInvoice_ClientOrderStatus.Text & "','" & txtClientNumber_ClientOrderStatus.Text.Replace("'", "\'") & "','" & txtFname_ClientOrderStatus.Text.Replace("'", "\'") & _
"', '" & txtLname_ClientOrderStatus.Text.Replace("'", "\'") & "', #ProductID" & i.ToString & ", #Name" & i.ToString & ", #Price" & i.ToString & _
", #Quantity" & i.ToString & ", #Description" & i.ToString & ", '" & txtTotal_ClientOrderStatus.Text & "',now())"
Command.Parameters.AddWithValue("#ProductID" & i.ToString, ListView1.Items(i).Text)
Command.Parameters.AddWithValue("#Name" & i.ToString, ListView1.Items(i).SubItems(1).Text)
Command.Parameters.AddWithValue("#Price" & i.ToString, ListView1.Items(i).SubItems(2).Text)
Command.Parameters.AddWithValue("#Quantity" & i.ToString, ListView1.Items(i).SubItems(3).Text)
Command.Parameters.AddWithValue("#Description" & i.ToString, ListView1.Items(i).SubItems(4).Text)
query &= ", "
Next
query = query.Substring(0, query.Length - 2)
I want to parameterized my query so instead of this code (This is a working code, I didn't put all the codes here because we have nothing to do with it.)
MySQL_Query = "SET #row_number = 0; " _
& "SELECT hardware_add " _
& "FROM (" _
& "SELECT " _
& "#row_number:=#row_number + 1 AS num, " _
& "hardware_add AS hardware_add " _
& "FROM teller_info " _
& "WHERE status = 'Disconnected'" _
& ") AS sub_query " _
& "WHERE num = " & counter & ";"
Console.WriteLine(MySQL_Query)
Dim MySQL_CMD As New MySqlCommand(MySQL_Query, MysqlConn)
MySQL_CMD.Connection.Open()
I changed it to this.
MySQL_Query = "SET #row_number = 0; " _
& "SELECT hardware_add " _
& "FROM (" _
& "SELECT " _
& "#row_number:=#row_number + 1 AS num, " _
& "hardware_add AS hardware_add " _
& "FROM teller_info " _
& "WHERE status = 'Disconnected'" _
& ") AS sub_query " _
& "WHERE num = ?;"
Console.WriteLine(MySQL_Query)
Dim MySQL_CMD As New MySqlCommand(MySQL_Query, MysqlConn)
MySQL_CMD.Connection.Open()
MySQL_CMD.Parameters.Add(New MySqlParameter("counter", counter))
The error says
MySql.Data.MySqlClient.MySqlException (0x80004005): Mixing named and unnamed parameters is not allowed.
My question is how can I properly parameterize that query?
You have to give a name to that param, doing so:
MySQL_Query = "SET #row_number = 0; " _
& "SELECT hardware_add " _
& "FROM (" _
& "SELECT " _
& "#row_number:=#row_number + 1 AS num, " _
& "hardware_add AS hardware_add " _
& "FROM teller_info " _
& "WHERE status = 'Disconnected'" _
& ") AS sub_query " _
& "WHERE num = #counter;"
Console.WriteLine(MySQL_Query)
Dim MySQL_CMD As New MySqlCommand(MySQL_Query, MysqlConn)
MySQL_CMD.Connection.Open()
MySQL_CMD.Parameters.Add(New MySqlParameter("#counter", counter))