Some values do not store in the database - mysql

i have this code:
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
If txtCode.Text <> "878" Then
If ((txtCode.Text <> "") And (txtRefNo.Text <> "") And (txtPayee.Text <> "") And (txtOffice.Text <> "") And (txtAddress.Text <> "") And (txtParticulars.Text <> "") And (txtPPA.Text <> "") And (txtAmount.Text <> "")) Then
Try
If IsNumeric(txtAmount.Text) = False Then
MsgBox("Amount value should be in correct number format! e.g: 10000.00 or 10,000.00", MsgBoxStyle.Exclamation)
Exit Sub
End If
modGlobalFunctions.Connection.Close()
modGlobalFunctions.connectDatabase()
modGlobalFunctions.DateTimeNow = String.Format("{0:yyyy/MM/dd}", DateTime.Now)
Dim Reader As MySqlDataReader
Dim Amount As Double = Double.Parse(txtAmount.Text)
Reader = modGlobalFunctions.executeQuery("SELECT * FROM obligations " & _
"WHERE ref_no='" & txtRefNo.Text & "'")
If Reader.HasRows Then
MessageBox.Show("Could not insert duplicate entries for REFERENCE NO.!", "Form Validations", MessageBoxButtons.OK, MessageBoxIcon.Error)
Reader.Close()
modGlobalFunctions.Connection.Close()
Else
modGlobalFunctions.Connection.Close()
modGlobalFunctions.connectDatabase()
modGlobalFunctions.executeNonQuery("INSERT INTO obligations (resp_id, year_id, expenditure_id, ref_no, payee, office, address, particulars, ppa, amount, date_entered, date_edited, signature1, position1, signature2, position2) " & _
"VALUES ('" & RespCenterId & "', " & _
"'" & YearId & "', " & _
"'" & txtExpId.Text & "', " & _
"'" & modGlobalFunctions.addslashes(txtRefNo.Text) & "', " & _
"'" & modGlobalFunctions.addslashes(txtPayee.Text) & "', " & _
"'" & modGlobalFunctions.addslashes(txtOffice.Text) & "', " & _
"'" & modGlobalFunctions.addslashes(txtAddress.Text) & "', " & _
"'" & modGlobalFunctions.addslashes(txtParticulars.Text) & "', " & _
"'" & modGlobalFunctions.addslashes(txtPPA.Text) & "', " & _
"'" & Amount & "', " & _
"'" & modGlobalFunctions.DateTimeNow & "', " & _
"'" & modGlobalFunctions.DateTimeNow & "', " & _
"'" & Signature1 & "', " & _
"'" & Position1 & "', " & _
"'" & Signature2 & "', " & _
"'" & Position2 & "')")
MsgBox("Record has been added!", MsgBoxStyle.Information)
modGlobalFunctions.Connection.Close()
Me.Close()
Dispose()
frmObligations.MdiParent = frmMain
frmObligations.Show()
frmObligations.obligationLoadGrid()
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "BIMS", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Else
MsgBox("Please fill up all form fields!", MsgBoxStyle.Exclamation)
modGlobalFunctions.Connection.Close()
End If
modGlobalFunctions.Connection.Close()
Else
If ((txtCode.Text <> "") And (txtRefNo.Text <> "") And (txtPayee.Text <> "") And (txtOffice.Text <> "") And (txtAddress.Text <> "") And (txtParticulars.Text <> "")) Then
Try
modGlobalFunctions.Connection.Close()
modGlobalFunctions.connectDatabase()
modGlobalFunctions.DateTimeNow = String.Format("{0:yyyy/MM/dd}", DateTime.Now)
Dim Reader As MySqlDataReader
Reader = modGlobalFunctions.executeQuery("SELECT * FROM obligations " & _
"WHERE ref_no='" & txtRefNo.Text & "'")
If Reader.HasRows Then
MessageBox.Show("Could not insert duplicate entries for REFERENCE NO.!", "Form Validations", MessageBoxButtons.OK, MessageBoxIcon.Error)
Reader.Close()
modGlobalFunctions.Connection.Close()
Else
modGlobalFunctions.Connection.Close()
modGlobalFunctions.connectDatabase()
modGlobalFunctions.executeNonQuery("INSERT INTO obligations (resp_id, year_id, expenditure_id, ref_no, payee, office, address, particulars, date_entered, date_edited, signature1, position1, signature2, position2) " & _
"VALUES ('" & RespCenterId & "', " & _
"'" & YearId & "', " & _
"'" & txtExpId.Text & "', " & _
"'" & modGlobalFunctions.addslashes(txtRefNo.Text) & "', " & _
"'" & modGlobalFunctions.addslashes(txtPayee.Text) & "', " & _
"'" & odGlobalFunctions.addslashes(txtOffice.Text) & "', " & _
"'" & modGlobalFunctions.addslashes(txtAddress.Text) & "', " & _
"'" & modGlobalFunctions.addslashes(txtParticulars.Text) & "', " & _
"'" & modGlobalFunctions.DateTimeNow & "', " & _
"'" & modGlobalFunctions.DateTimeNow & "', " & _
"'" & Signature1 & "', " & _
"'" & Position1 & "', " & _
"'" & Signature2 & "', " & _
"'" & Position2 & "')")
MsgBox("Record has been added! You can now add project title!", MsgBoxStyle.Information)
frmProject.MdiParent = frmMain
frmProject.Show()
frmProject.Label2.Text = txtRefNo.Text
Me.Enabled = False
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "BIMS", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Else
MsgBox("Please fill up all form fields!", MsgBoxStyle.Exclamation)
modGlobalFunctions.Connection.Close()
End If
modGlobalFunctions.Connection.Close()
End If
End Sub
What do you think is the problem why Signature1, Position1, Signature2 and Position2 doesn't store in the database. It works fine before until i put the if code because of the category... by the way here's the code for signature1, position1, signature2 and position2:
Signature1:
Private Sub cbSignatory1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
Try
modGlobalFunctions.Connection.Close()
modGlobalFunctions.connectDatabase()
Reader = modGlobalFunctions.executeQuery("SELECT person_id FROM persons WHERE person_name='" & cbSignatory1.Text & "'")
If Reader.HasRows Then
While Reader.Read
Signature1 = Reader("person_id").ToString()
End While
End If
Reader.Close()
modGlobalFunctions.Connection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "BIMS", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
modGlobalFunctions.Connection.Close()
End Sub
Signature2:
Private Sub cbSignatory2_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
Try
modGlobalFunctions.Connection.Close()
modGlobalFunctions.connectDatabase()
Reader = modGlobalFunctions.executeQuery("SELECT person_id FROM persons WHERE person_name='" & cbSignatory2.Text & "'")
If Reader.HasRows Then
While Reader.Read
Signature2 = Reader("person_id").ToString()
End While
End If
Reader.Close()
modGlobalFunctions.Connection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "BIMS", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
modGlobalFunctions.Connection.Close()
End Sub
Position1:
Private Sub cbPosition1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
Try
modGlobalFunctions.Connection.Close()
modGlobalFunctions.connectDatabase()
Reader = modGlobalFunctions.executeQuery("SELECT position_id FROM positions WHERE position_name='" & cbPosition1.Text & "'")
If Reader.HasRows Then
While Reader.Read
Position1 = Reader("position_id").ToString()
End While
End If
Reader.Close()
modGlobalFunctions.Connection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "BIMS", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
modGlobalFunctions.Connection.Close()
End Sub
Position2:
Private Sub cbPosition2_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
Try
modGlobalFunctions.Connection.Close()
modGlobalFunctions.connectDatabase()
Reader = modGlobalFunctions.executeQuery("SELECT position_id FROM positions WHERE position_name='" & cbPosition2.Text & "'")
If Reader.HasRows Then
While Reader.Read
Position2 = Reader("position_id").ToString()
End While
End If
Reader.Close()
modGlobalFunctions.Connection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "BIMS", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
modGlobalFunctions.Connection.Close()
End Sub
any suggestions?

I bet Person_ID and position_id are numeric types in your database. Right? The reason it's not inserting because you wrapped it with single quotes:
"'" & Signature1 & "', " & _ // <== here
"'" & Position1 & "', " & _
"'" & Signature2 & "', " & _
"'" & Position2 & "'
Numeric values are not wrap with single quotes. One more thing, I suggest you use Command and parameters to avoid SQL Injection.
Example based on your code:
Dim sqlStatement AS String = "INSERT INTO obligations (resp_id, year_id, expenditure_id, "
sqlStatement &= "ref_no, payee, office, address, particulars, ppa, amount, date_entered, "
sqlstetement &= "date_edited, signature1, position1, signature2, position2) "
sqlstetement &= "VALUES (#resp_id, #year_id, #expenditure_id, "
sqlStatement &= "#ref_no, #payee, #office, #address, #particulars, #ppa, #amount, #date_entered, "
sqlstetement &= "#date_edited, #signature1, #position1, #signature2, #position2) "
Using xConn AS New MySQLConnection(connStrHere)
Using xComm AS New MySQLCommand()
With xComm
.Connection = xConn
.CommandType = CommandType.Text
.CommandText = sqlStatement
.Parameter.AddWithValue("#resp_id", RespCenterId)
.Parameter.AddWithValue("#year_id", YearId)
.Parameter.AddWithValue("#expenditure_id", txtExpId.Text)
' continue with other parameters
' .....
' until you reach the last parameters '
.Parameter.AddWithValue("#signature1", Signature1)
.Parameter.AddWithValue("#position1", Position1)
.Parameter.AddWithValue("#signature2", Signature2)
.Parameter.AddWithValue("#position2", Position2)
End With
Try
xConn.Open()
xComm.ExecuteNonQuery()
MsgBox("Record has been added!", MsgBoxStyle.Information)
Catch ex AS MySQLException
MsgBox(e.Message, MsgBoxStyle.Exclamation)
Finally
xConn.Open()
End try
End Using
End Using

Related

How to save edited data record in access form as a new record?

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

Access vba function getting stopping when other form opens as part of function

I have the following function running on form load when the database opens. I know something is missing but I am not sure what exactly. The code runs fine until it opens a form so the user can select a printer. Then the form has it's own that it works through.
I put a break in and the code stops on the SelectPrinter sub so I guess I need that code to return to the function or can I write the code into the function?
This is the function:
Option Compare Database
Function PrintReports()
Dim ExeCount As Long
Dim ExdCount As Long
Dim ExiCount As Long
Dim ExnCount As Long
Dim ExpCount As Long
Dim Answer As Integer
DoCmd.SetWarnings (WarningsOff)
'Create Ex e Table
DoCmd.RunSQL "SELECT tbl_AHAD.*, IIf([Last_Insp_Date] Is Null,Date(),DateAdd('yyyy',4,[Last_Insp_Date]))
AS Due_Date " & _
"INTO tbl_Ex_e " & _
"FROM tbl_AHAD " & _
"WHERE (((IIf([Last_Insp_Date] Is Null,Date(),DateAdd('yyyy',4,
[Last_Insp_Date])))<=Date()) " & _
"AND ((tbl_AHAD.Device_Class) In ('Ex e','Ex eb','Ex ed','Ex em','Ex
emb','Ex mb','Ex mbe','Ex me')))" & _
"ORDER BY tbl_AHAD.Maint_Item"
'Create Ex d Table
DoCmd.RunSQL "SELECT tbl_AHAD.*, IIf([Last_Insp_Date] Is
Null,Date(),DateAdd('yyyy',4,[Last_Insp_Date])) AS Due_Date " & _
"INTO tbl_Ex_d " & _
"FROM tbl_AHAD " & _
"WHERE (((IIf([Last_Insp_Date] Is Null,Date(),DateAdd('yyyy',4,
[Last_Insp_Date])))<=Date()) " & _
"AND ((tbl_AHAD.Device_Class) In ('Class 1','Ex d','Ex de','Ex dmb')))" & _
"ORDER BY tbl_AHAD.Maint_Item"
'Create Ex i Table
DoCmd.RunSQL "SELECT tbl_AHAD.*, IIf([Last_Insp_Date] Is
Null,Date(),DateAdd('yyyy',4,[Last_Insp_Date])) AS Due_Date " & _
"INTO tbl_Ex_i " & _
"FROM tbl_AHAD " & _
"WHERE (((IIf([Last_Insp_Date] Is Null,Date(),DateAdd('yyyy',4,
[Last_Insp_Date])))<=Date()) " & _
"AND ((tbl_AHAD.Device_Class) In ('Ex i','Ex ia')))" & _
"ORDER BY tbl_AHAD.Maint_Item"
'Create Ex n Table
DoCmd.RunSQL "SELECT tbl_AHAD.*, IIf([Last_Insp_Date] Is
Null,Date(),DateAdd('yyyy',4,[Last_Insp_Date])) AS Due_Date " & _
"INTO tbl_Ex_n " & _
"FROM tbl_AHAD " & _
"WHERE (((IIf([Last_Insp_Date] Is Null,Date(),DateAdd('yyyy',4,
[Last_Insp_Date])))<=Date()) " & _
"AND ((tbl_AHAD.Device_Class) In ('Ex n','Ex nA','Ex nR')))" & _
"ORDER BY tbl_AHAD.Maint_Item"
'Create Ex p Table
DoCmd.RunSQL "SELECT tbl_AHAD.*, IIf([Last_Insp_Date] Is
Null,Date(),DateAdd('yyyy',4,[Last_Insp_Date])) AS Due_Date " & _
"INTO tbl_Ex_p " & _
"FROM tbl_AHAD " & _
"WHERE (((IIf([Last_Insp_Date] Is Null,Date(),DateAdd('yyyy',4,
[Last_Insp_Date])))<=Date()) " & _
"AND ((tbl_AHAD.Device_Class) In ('Ex p'))) " & _
"ORDER BY tbl_AHAD.Maint_Item"
DoCmd.SetWarnings (WarningsOff)
'Open message box to ensure user wants to continue
ExeCount = DCount("ID", "tbl_Ex_e")
ExdCount = DCount("ID", "tbl_Ex_d")
ExiCount = DCount("ID", "tbl_Ex_i")
ExnCount = DCount("ID", "tbl_Ex_n")
ExpCount = DCount("ID", "tbl_Ex_p")
Answer = MsgBox("There are " & vbCrLf & vbCrLf & ExeCount & " Ex e Reports
" & vbCrLf & ExdCount & " Ex d Reports " & vbCrLf & _
ExiCount & " Ex i Reports" & vbCrLf & ExnCount & " Ex n Reports" &
vbCrLf & ExpCount & " Ex p Reports" & _
vbCrLf & vbCrLf & "Records to Print", vbOKCancel)
'If Ok then print all reports
If Answer = vbOK Then
DoCmd.OpenForm "SelectPrinter", , , , , acDialog
**'Stopping here**
Set Application.Printer = _
Application.Printers(cboDestination.ListIndex)
DoCmd.Close acForm, "SelectPrinter", acSaveYes
If ExpCount > 0 Then
DoCmd.OpenReport "rpt_Ex_p"
End If
' Switch back to original default printer
Set Application.Printer = Application.Printers(strDefaultPrinter)
Else
Exit Function
End If
'Update table with today's date
DoCmd.RunSQL "UPDATE tbl_AHAD INNER JOIN tbl_Ex_p ON tbl_AHAD.ID = tbl_Ex_p.ID " & _
"SET tbl_AHAD.Last_Insp_Date = Date() "
End Function
This is the sub that runs along with it's function after the DoCmd.OpenForm "SelectPrinter", , , , , acDialog
Private Sub Form_Load()
cboDestination = ""
m_GetPrinters cboDestination
cboDestination.SetFocus
cboDestination.ListIndex = 0
End Sub
Public Sub m_GetPrinters(ByRef objListOrCombo As Object)
Dim objPrinter As Printer
Dim intNbOfPrinters As Integer
intNbOfPrinters = Printers.Count - 1
For Each objPrinter In Printers
objListOrCombo.AddItem objPrinter.DeviceName
Next
End Sub
You specifically open the form in dialogue mode:
DoCmd.OpenForm "SelectPrinter", , , , , acDialog
Thus, your code will not stop, but it turns to the form opened and silently waits until that form is closed - then the code will proceed.
If you wish to open the form and have the function PrintReports() to continue without taking notice of the form, then don't use the acDialog setting.

Save Listview item with multiple rows and columns to Mysql Database

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)

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.

error database: Syntax error in INSERT INTO statement

I'm having difficulties with my library system. I get an error that states "error database: Syntax error in INSERT INTO statement". I'm using Access for the data base.
Here's my code:
Public Class Form7
Private Sub Form7_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
Me.Text = "Registration"
sqlCon.Close()
sqlCon.Close()
clear()
End Sub
Private Sub Form7_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Split(Me.Text, " - ")(1) = "Edit" Then
sqlSTR = "Select * From BookRegister WHERE id = " & globalID
ExecuteSQLQuery(sqlSTR)
If sqlDr.Read Then
TextBox1.Text = sqlDr(1)
TextBox2.Text = sqlDr(2)
TextBox3.Text = sqlDr(3)
TextBox4.Text = sqlDr(4)
TextBox5.Text = sqlDr(5)
TextBox6.Text = sqlDr(6)
TextBox7.Text = sqlDr(7)
TextBox7.Text = sqlDr(8)
End If
End If
End Sub
Private Sub TextBox6_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox6.TextChanged
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If TextBox1.Text = "" Then
MsgBox("Please fill up all the information", MsgBoxStyle.Information)
ElseIf TextBox2.Text = "" Then
MsgBox("Please fill up all the information", MsgBoxStyle.Information)
ElseIf TextBox3.Text = "" Then
MsgBox("Please fill up your information", MsgBoxStyle.Information)
ElseIf TextBox4.Text = "" Then
MsgBox("Please fill up your information", MsgBoxStyle.Information)
ElseIf TextBox5.Text = "" Then
MsgBox("Please fill up your information", MsgBoxStyle.Information)
ElseIf TextBox6.Text = "" Then
MsgBox("Please fill up your information", MsgBoxStyle.Information)
ElseIf TextBox7.Text = "" Then
MsgBox("Please fill up all the information", MsgBoxStyle.Information)
ElseIf TextBox8.Text = "" Then
MsgBox("Please fill up all the information", MsgBoxStyle.Information)
ElseIf Split(Me.Text, " - ")(1) = "Add" Then
sqlSTR = "INSERT INTO BookRegister(ISBN, Title, Author, Volume, Pages, Publisher, Section, Year_Published) " & _
"VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "'" & _
",'" & TextBox6.Text & "','" & TextBox7.Text & "','" & TextBox8.Text & ")"""
ExecuteSQLQuery(sqlSTR)
MsgBox("New record has been saved.", MsgBoxStyle.Information)
clear()
Else
sqlSTR = "UPDATE BookRegister SET ISBN ='" & TextBox1.Text & "', " & _
"title='" & TextBox2.Text & "', " & _
"author='" & TextBox3.Text & "', " & _
"volume='" & TextBox4.Text & "', " & _
"pages='" & TextBox5.Text & "', " & _
"publisher='" & TextBox6.Text & "', " & _
"section='" & TextBox7.Text & "', " & _
"year_published='" & Format("yyyy", TextBox8.Text) & "', " & _
" WHERE id =" & globalID
ExecuteSQLQuery(sqlSTR)
MsgBox("Record has been updated !!", MsgBoxStyle.Information)
clear()
globalID = 0
edit = False
Me.Close()
End If
FillListView(Form6.ListView1, ExecuteSQLQuery("select * from bookregister"))
End Sub
Private Sub clear()
Textbox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
TextBox5.Text = ""
TextBox6.Text = ""
TextBox7.Text = ""
TextBox8.Text = ""
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Me.Close()
End Sub
End Class
It looks like you are missing a final single quote at the end of your INSERT statement, and then appending an extraneous double quote after the closing parenthesis, i.e.,
& "','" & TextBox8.Text & ")"""
should be
& "','" & TextBox8.Text & "')"