I'm getting this error when I click the update button in my form:
" An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Incorrect syntax near 'intGenderID'."
The update does not work.
Could anyone point me in the right direction? Thanks in advance!
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim strSelect As String = ""
Dim strFirstName As String = ""
Dim strLastName As String = ""
Dim strAddress As String = ""
Dim strCity As String = ""
Dim strState As String = ""
Dim strZip As String = ""
Dim strPhoneNumber As String = ""
Dim strEmail As String = ""
Dim intRowsAffected As Integer
Dim cmdUpdate As OleDb.OleDbCommand
If Validation() = True Then
' open database
If OpenDatabaseConnectionSQLServer() = False Then
' No, warn the user ...
MessageBox.Show(Me, "Database connection error." & vbNewLine &
"The application will now close.",
Me.Text + " Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End If
If Validation() = True Then
strFirstName = txtFirstName.Text
strLastName = txtLastName.Text
strAddress = txtAddress.Text
strCity = txtCity.Text
strState = txtState.Text
strZip = txtZip.Text
strPhoneNumber = txtPhoneNumber.Text
strEmail = txtEmail.Text
strSelect = "Update TGolfers Set strFirstName = '" & strFirstName & "', " & "strLastName = '" & strLastName &
"', " & "strAddress = '" & strAddress & "', " & "strCity = '" & strCity & "', " &
"strState = '" & strState & "', " & "strZip = '" & strZip & "', " &
"strPhoneNumber = '" & strPhoneNumber & "', " & "strEmail = '" & strEmail & "', " &
"intShirtSizeID = '" & cboShirtSizes.SelectedValue.ToString & "' " &
"intGenderID = '" & cboGenders.SelectedValue.ToString & "' " &
"Where intGolferID = " & cboGolfers.SelectedValue.ToString
MessageBox.Show(strSelect)
cmdUpdate = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
intRowsAffected = cmdUpdate.ExecuteNonQuery()
If intRowsAffected = 1 Then
MessageBox.Show("Update successful")
Else
MessageBox.Show("Update failed")
End If
CloseDatabaseConnection()
frmManageGolfers_Load(sender, e)
End If
End If
End Sub
Syntax error means that the SQL isn't the right syntax. Its quite strict.
Near 'intGenderID' means the syntax error is just before this. In your case, you've missed a comma.
I will proceed as if this MySql. Keep your database objects local. You need to keep track that they are closed and disposed. `Using...End Using blocks take care of this even if there is an error.
Always use parameters. Not only does it make writing the sql statement much easier it will save your database from sql injection.
Additional comments in-line.
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim intRowsAffected As Integer
Dim strSelect As String = "Update TGolfers Set strFirstName = #FirstName, strLastName = #LastName, strAddress = #Address, strCity = #City, strState = #State, strZip = #Zip, strPhoneNumber = #Phone, strEmail = #EMail, intShirtSizeID = #ShirtSize, intGenderID = #Gender Where intGolferID = #GolferID;"
If Not Validation() Then
'Actually the input should be validated before we get here
MessageBox.Show("Did not pass validation. Correct the input")
Return
End If
Using cn As New MySqlConnection("Your connection string")
Using cmd As New MySqlCommand(strSelect, cn)
cmd.Parameters.Add("#FirstName", MySqlDbType.VarChar).Value = txtFirstName.Text
cmd.Parameters.Add("#LastName", MySqlDbType.VarChar).Value = txtLastName.Text
cmd.Parameters.Add("#Address", MySqlDbType.VarChar).Value = txtAddress.Text
cmd.Parameters.Add("#City", MySqlDbType.VarChar).Value = txtCity.Text
cmd.Parameters.Add("#State", MySqlDbType.VarChar).Value = txtState.Text
cmd.Parameters.Add("#Zip", MySqlDbType.VarChar).Value = txtZip.Text
cmd.Parameters.Add("#Phone", MySqlDbType.VarChar).Value = txtPhoneNumber.Text
cmd.Parameters.Add("#EMail", MySqlDbType.VarChar).Value = txtEmail.Text
'Are you sure you have set the .ValueMember of the combo boxes?
cmd.Parameters.Add("#ShirtSize", MySqlDbType.VarChar).Value = cboShirtSizes.SelectedValue.ToString
cmd.Parameters.Add("#Gender", MySqlDbType.VarChar).Value = cboGenders.SelectedValue.ToString
'Are your sure that intGolferID is not a number
cmd.Parameters.Add("#GolferID", MySqlDbType.Int32).Value = cboGolfers.SelectedValue
cn.Open()
intRowsAffected = cmd.ExecuteNonQuery()
End Using
End Using
If intRowsAffected = 1 Then
MessageBox.Show("Update successful")
Else
MessageBox.Show("Update failed")
End If
frmManageGolfers.Show() 'I can't image why you would try to send a button and the button's event args to the Load event of another form
End Sub
Related
I'm trying to insert a barcode image into database using AxBarCodeWiz, it's a tool that generates barcode and is displayed as a picturebox and I can edit the barcode using its built in property.
My problem is when I try to insert the barcode into database I get this error saying "Column count doesn't match value count at row 1". I thought it's because i'm using a wrong datatype in my database so I changed its datatype to BLOB but the still error also tried CHAR but still the same error.
This is the code I use to insert values into database if it is important
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim insertbarcode As String = "INSERT INTO eeldatabase.barcode(Barcode, ItemCode, Operation, BundleNumber, Color, Size, Quantity, Price, Amount) values( '" & AxBarCodeWiz3.Barcode & "', '" & txtItemCode.Text & "', '" & txtOperation.Text & "', '" & txtBundleNo.Text & "', '" & txtColor.Text & "', '" & txtSize.Text & "' '" & txtQuantity.Text & "', '" & txtPrice.Text & "', '" & txtAmount.Text & "')"
Dim answer As Integer
If txtItemCode.Text = "" Or txtOperation.Text = "" Or txtBundleNo.Text = "" Or txtColor.Text = "" Or txtSize.Text = "" Or txtQuantity.Text = "" Or txtPrice.Text = "" Or txtAmount.Text = "" Then
MessageBox.Show("Please complete the required fields!", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
answer = MsgBox("Add this Barcode to the database?", vbYesNo + vbQuestion, "Add Barcode")
If answer = vbYes Then
ExecuteQuery(insertbarcode)
MessageBox.Show("Barcode successfuly added!")
connection.Close()
connection.Dispose()
txtItemCode.Text = ""
txtOperation.Text = ""
txtBundleNo.Text = ""
txtColor.Text = ""
txtSize.Text = ""
txtQuantity.Text = ""
txtPrice.Text = ""
txtAmount.Text = ""
Else
MessageBox.Show("Barcode not inserted")
txtItemCode.Text = ""
txtOperation.Text = ""
txtBundleNo.Text = ""
txtColor.Text = ""
txtSize.Text = ""
txtQuantity.Text = ""
txtPrice.Text = ""
txtAmount.Text = ""
End If
connection.Close()
Dim table As New DataTable()
Dim adapter As New MySqlDataAdapter("SELECT * FROM eeldatabase.barcode", connection)
adapter.Fill(table)
dgvBarcode.DataSource = table
End If
End Sub
Is it possible to insert this barcode to my database or is it not? If not can I just use its text value to be inserted in the database because the main purpose of this is for the user to be able to scan a barcode and retrieve that barcode that is saved in the database so even a text value would be okay to use.
While testing my program, an error popped up saying, "Too many connections" when I tried to log in an another user.
I need to fix it so that the connections aren't left open to time out on their own, so that it runs perfectly.
Private Sub addstub()
Using connection As New MySqlConnection(connectionstring)
SQL = "SELECT count(*) from remaining_ham where Stub=#stub and Emp_No LIKE '%" & txtid.Text & "%'"
Using Command As New MySqlCommand(SQL, connection)
Command.Parameters.AddWithValue("#stub", txtclaim.Text)
Command.Parameters.AddWithValue("#claim", "CLAIMED")
Command.CommandText = SQL
connection.Open()
Dim count As Integer = Command.ExecuteScalar
If count = 1 Then
MsgBox("PROCESSING")
Using connection2 As New MySqlConnection(connectionstring)
SQL = "Select count(*) from remaining_ham where status='CLAIMED' and Stub='" & txtclaim.Text & "' and Emp_No LIKE'%" & txtid.Text & "%' "
Using command2 As New MySqlCommand(SQL, connection)
connection2.Open()
Dim i1 As Integer = command2.ExecuteScalar()
If i1 = 1 Then
MsgBox("ALREADY CLAIMED")
Else
Using connection3 As New MySqlConnection(connectionstring)
SQL = "Select Stub,Total,Brickham,Jamon,Fiesta,status from remaining_ham where Stub='" & txtclaim.Text & "' and Emp_No LIKE'%" & txtid.Text & "%' "
Using myAdapter As New MySqlDataAdapter(SQL, connection)
Dim table = New DataSet
myAdapter.Fill(table)
txtbrick.Text = table.Tables(0).Rows(0)("Brickham").ToString
txtjamon.Text = table.Tables(0).Rows(0)("Jamon").ToString
txtfiesta.Text = table.Tables(0).Rows(0)("Fiesta").ToString
txttotal.Text = table.Tables(0).Rows(0)("Total").ToString
If MsgBox("ARE YOU SURE?" + Environment.NewLine + "Stub No: " + txtid.Text + Environment.NewLine + "Brickham: " + txtbrick.Text + Environment.NewLine + "Jamon De Bola: " + txtjamon.Text + Environment.NewLine + "Fiesta Ham: " + txtfiesta.Text, MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
'MsgBox("TAMA")
jam = CDbl(txtjamon.Text)
rmham = CDbl(txtremjamon.Text)
txtremjamon.Text = (rmham - jam).ToString
Dim dbjam = Format(CDbl(txtremjamon.Text), "#,###")
If dbjam = "" Then
dbjam = 0
End If
brk = CDbl(txtbrick.Text)
rembrk = CDbl(txtrembrick.Text)
txtrembrick.Text = (rembrk - brk).ToString
Dim dbbrick = Format(CDbl(txtrembrick.Text), "#,###")
If dbbrick = "" Then
dbbrick = 0
End If
fiesta = CDbl(txtfiesta.Text)
rmfiesta = CDbl(txtremfiesta.Text)
txtremfiesta.Text = (rmfiesta - fiesta).ToString
Dim dbfiesta = Format(CDbl(txtremfiesta.Text), "#,###")
If dbfiesta = "" Then
dbfiesta = 0
End If
total = CDbl(txttotal.Text)
rmtotal = CDbl(txtremtotal.Text)
txtremtotal.Text = (rmtotal - total).ToString
Dim dbtotal = Format(CDbl(txtremtotal.Text), "#,###")
If dbtotal = "" Then
dbtotal = 0
End If
Using connection4 As New MySqlConnection(connectionstring)
SQL = "UPDATE order_ham SET rem_brick='" & dbbrick & "', rem_jam='" & dbjam & "', rem_fiesta='" & dbfiesta & "', rem_total='" & dbtotal & "' where Emp_No=" & txtid.Text & " "
Using command3 As New MySqlCommand(SQL, connection4)
connection4.Open()
Dim i As Integer = command3.ExecuteNonQuery
If i = 0 Then
MsgBox("WRONG")
Exit Sub
Else
' MsgBox("RIGHT")
Using connection5 As New MySqlConnection(connectionstring)
Dim date1 As Date = Date.Today
SQL = "UPDATE remaining_ham SET status='CLAIMED',ddate='" & DateTime.Now & "' where Stub='" + txtclaim.Text + "' and Emp_No LIKE '%" + txtid.Text + "%' "
Using command4 As New MySqlCommand(SQL, connection5)
connection5.Open()
Dim a As Integer = command4.ExecuteNonQuery
connection5.Close()
If a = 0 Then
MsgBox("not claim: ERROR ")
Exit Sub
Else
MsgBox("SUCCESS")
Using da As New MySqlDataAdapter(SQL, connection5)
Dim dt As New DataTable
da.Fill(dt)
MetroGrid1.DataSource = Nothing
MetroGrid1.Rows.Clear()
MetroGrid3.DataSource = Nothing
MetroGrid3.Rows.Clear()
loadRemainingHam()
remainingorder()
txtclaim.Focus()
End Using
End If
End Using
End Using
End If
End Using
End Using
Else
MsgBox("CANCELLED")
End If
End Using
End Using
End If
End Using
End Using
Else
MsgBox("ERROR")
End If
End Using
End Using
End Sub
Thank you for those who will answer.
You can perform multiple commands/actions with 1 connection.
You could try something like this:
Dim connection As New MySqlConnection(connectionstring)
connection.Open()
Dim SQL as String = "SELECT count(*) from remaining_ham where Stub=#stub and Emp_No LIKE '%" & txtid.Text & "%'"
Using ObjCommand As New MySqlCommand(SQL, connection)
ObjCommand.Parameters.AddWithValue("#stub", txtclaim.Text)
ObjCommand.Parameters.AddWithValue("#claim", "CLAIMED")
ObjCommand.CommandText = SQL
Dim count As Integer = Command.ExecuteScalar
If count = 1 Then
MsgBox("PROCESSING")
SQL = "Select count(*) from remaining_ham where status='CLAIMED' and Stub='" & txtclaim.Text & "' and Emp_No LIKE'%" & txtid.Text & "%' "
Using ObjCommand2 As New MySqlCommand(SQL, connection)
Dim i1 As Integer = command2.ExecuteScalar()
If i1 = 1 Then
MsgBox("ALREADY CLAIMED")
Else
SQL = "Select Stub,Total,Brickham,Jamon,Fiesta,status from remaining_ham where Stub='" & txtclaim.Text & "' and Emp_No LIKE'%" & txtid.Text & "%' "
Using myAdapter As New MySqlDataAdapter(SQL, connection)
//code here
End Using
End If
End Using
End If
End Using
connection.Close()
connection.Dispose()
What is the database of this program? can you please add ;pooling=false at the end of your mysqlconnection like this
server=localhost;user=root;database=world;port=3306;password=******;pooling=false
and try it
You have way to many queries inside of queries. Try to remove as much as possible. Here's an example with the first one.
You should close the connections as soon as possible.
Private Sub addstub()
'*** GET THE COUNT, CLOSE THE CONNECTION, NOT NEEDED ANYMORE.
Dim count As Integer
Using connection As New MySqlConnection(connectionstring)
SQL = "SELECT count(*) from remaining_ham where Stub=#stub and Emp_No LIKE '%" & txtid.Text & "%'"
Using Command As New MySqlCommand(SQL, connection)
Command.Parameters.AddWithValue("#stub", txtclaim.Text)
Command.Parameters.AddWithValue("#claim", "CLAIMED")
Command.CommandText = SQL
connection.Open()
count = Command.ExecuteScalar
End Using
End Using
If count = 1 Then
MsgBox("PROCESSING")
Using connection2 As New MySqlConnection(connectionstring)
SQL = "Select count(*) from remaining_ham where status='CLAIMED' and Stub='" & txtclaim.Text & "' and Emp_No LIKE'%" & txtid.Text & "%' "
Using command2 As New MySqlCommand(SQL, connection)
connection2.Open()
Dim i1 As Integer = command2.ExecuteScalar()
If i1 = 1 Then
MsgBox("ALREADY CLAIMED")
Else
Using connection3 As New MySqlConnection(connectionstring)
SQL = "Select Stub,Total,Brickham,Jamon,Fiesta,status from remaining_ham where Stub='" & txtclaim.Text & "' and Emp_No LIKE'%" & txtid.Text & "%' "
Using myAdapter As New MySqlDataAdapter(SQL, connection)
Dim table = New DataSet
myAdapter.Fill(table)
txtbrick.Text = table.Tables(0).Rows(0)("Brickham").ToString
txtjamon.Text = table.Tables(0).Rows(0)("Jamon").ToString
txtfiesta.Text = table.Tables(0).Rows(0)("Fiesta").ToString
txttotal.Text = table.Tables(0).Rows(0)("Total").ToString
If MsgBox("ARE YOU SURE?" + Environment.NewLine + "Stub No: " + txtid.Text + Environment.NewLine + "Brickham: " + txtbrick.Text + Environment.NewLine + "Jamon De Bola: " + txtjamon.Text + Environment.NewLine + "Fiesta Ham: " + txtfiesta.Text, MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
'MsgBox("TAMA")
jam = CDbl(txtjamon.Text)
rmham = CDbl(txtremjamon.Text)
txtremjamon.Text = (rmham - jam).ToString
Dim dbjam = Format(CDbl(txtremjamon.Text), "#,###")
If dbjam = "" Then
dbjam = 0
End If
brk = CDbl(txtbrick.Text)
rembrk = CDbl(txtrembrick.Text)
txtrembrick.Text = (rembrk - brk).ToString
Dim dbbrick = Format(CDbl(txtrembrick.Text), "#,###")
If dbbrick = "" Then
dbbrick = 0
End If
fiesta = CDbl(txtfiesta.Text)
rmfiesta = CDbl(txtremfiesta.Text)
txtremfiesta.Text = (rmfiesta - fiesta).ToString
Dim dbfiesta = Format(CDbl(txtremfiesta.Text), "#,###")
If dbfiesta = "" Then
dbfiesta = 0
End If
total = CDbl(txttotal.Text)
rmtotal = CDbl(txtremtotal.Text)
txtremtotal.Text = (rmtotal - total).ToString
Dim dbtotal = Format(CDbl(txtremtotal.Text), "#,###")
If dbtotal = "" Then
dbtotal = 0
End If
Using connection4 As New MySqlConnection(connectionstring)
SQL = "UPDATE order_ham SET rem_brick='" & dbbrick & "', rem_jam='" & dbjam & "', rem_fiesta='" & dbfiesta & "', rem_total='" & dbtotal & "' where Emp_No=" & txtid.Text & " "
Using command3 As New MySqlCommand(SQL, connection4)
connection4.Open()
Dim i As Integer = command3.ExecuteNonQuery
If i = 0 Then
MsgBox("WRONG")
Exit Sub
Else
' MsgBox("RIGHT")
Using connection5 As New MySqlConnection(connectionstring)
Dim date1 As Date = Date.Today
SQL = "UPDATE remaining_ham SET status='CLAIMED',ddate='" & DateTime.Now & "' where Stub='" + txtclaim.Text + "' and Emp_No LIKE '%" + txtid.Text + "%' "
Using command4 As New MySqlCommand(SQL, connection5)
connection5.Open()
Dim a As Integer = command4.ExecuteNonQuery
connection5.Close()
If a = 0 Then
MsgBox("not claim: ERROR ")
Exit Sub
Else
MsgBox("SUCCESS")
Using da As New MySqlDataAdapter(SQL, connection5)
Dim dt As New DataTable
da.Fill(dt)
MetroGrid1.DataSource = Nothing
MetroGrid1.Rows.Clear()
MetroGrid3.DataSource = Nothing
MetroGrid3.Rows.Clear()
loadRemainingHam()
remainingorder()
txtclaim.Focus()
End Using
End If
End Using
End Using
End If
End Using
End Using
Else
MsgBox("CANCELLED")
End If
End Using
End Using
End If
End Using
End Using
Else
MsgBox("ERROR")
End If
End Sub
The best thing you could do would be to put each query in a function. Also, parametrize everything!
Private Function GetClaimCount(ByVal id As String, ByVal claim As String) As Integer
Dim count As Integer = 0
Using connection As New MySqlConnection(connectionstring)
' id should be a parameter!!
SQL = "SELECT count(*) from remaining_ham where Stub=#stub and Emp_No LIKE '%" & id & "%'"
Using Command As New MySqlCommand(SQL, connection)
Command.Parameters.AddWithValue("#stub", claim)
Command.Parameters.AddWithValue("#claim", "CLAIMED")
Command.CommandText = SQL
connection.Open()
count = Command.ExecuteScalar
End Using
End Using
Return count
End Function
Private Sub addstub()
Dim count As Integer = GetClaimCount(txtid.Text, txtclaim.Text)
If count = 1 Then
MsgBox("PROCESSING")
' ...
Else
MsgBox("ERROR")
End If
End Sub
Recently i build a pos but the datagridview doesnt refresh i tried different methods but its not worikng
Dim Query As String
Query = "insert into bazaartikli123.artikli(id,barkod,naziv,kupovna,prodazna,opis) values ('" & TextBoxBarkod.Text & "','" & TextBoxNaziv.Text & "','" & TextBoxKupovna.Text & "','" & TextBoxProdazna.Text & "','" & TextBoxOpis.Text & "')"
COMMAND = New MySqlCommand(Query, konecija)
READER = COMMAND.ExecuteReader
Dim dataadapter As New SqlDataAdapter(sql, konekcija)
Dim ds As New DataSet()
MessageBox.Show("Артиклот е успешно внесен !")
TextBoxBarkod.Text = ""
TextBoxKupovna.Text = ""
TextBoxNaziv.Text = ""
TextBoxOpis.Text = ""
TextBoxProdazna.Text = ""
dataadapter.Fill(ds)
konecija.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Artikli"
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
konecija.Dispose()
End Try
Bazadataset ,ArtikliBindingSource , ArtikliTableAdapter
What I want to do is, check first if the ID number exist, then if it exist then do the updating process, but the problem is, it does not update. What is the problem ?
sqlconn = New MySqlConnection
sqlconn.ConnectionString = "server=localhost;userid=root;password='';database=innovative"
Try
sqlconn.Open()
query = "SELECT Full_Name FROM employee WHERE ID='" & txt_id_number.Text & "'"
cmd = New MySqlCommand(query, sqlconn)
reader = cmd.ExecuteReader
If reader.HasRows = False Then
MsgBox("Invalid ID number please secure that the ID number is already Exist" & vbNewLine & "TAKE NOTE:" & vbNewLine & "You cannot update or change the existing ID number for it is the primary Key for the Employee, If you want to Change it, its better to delete the Employee then add it again." & vbNewLine & "Other than that you can change the Full name, age, contact and etc.", vbCritical)
Else
reader.Close()
sqlconn.Open()
query1 = "UPDATE employee SET Full_Name ='" & txt_fullname.Text & "', Employee_Type='" & txt_employee_type.Text & "', Age='" & txt_age.Text & "',Sex='" & cb_sex.Text & "', Status='" & txt_status.Text & "', Contact ='" & txt_contact.Text & "',E_mail='" & txt_email.Text & "' WHERE ID = '" & txt_id_number.Text & "'"
cmd = New MySqlCommand(query1, sqlconn)
reader1 = cmd.ExecuteReader
MsgBox(txt_fullname.Text & " was successfully updated", vbInformation)
txt_age.Text = ""
txt_contact.Text = ""
txt_email.Text = ""
txt_employee_type.Text = ""
txt_fullname.Text = ""
txt_id_number.Text = ""
txt_status.Text = ""
cb_sex.Text = ""
add_employee()
End If
sqlconn.Close()
Catch ex As Exception
Finally
sqlconn.Dispose()
End Try
Imports MySql.Data.MySqlClient
Public Class Form1
Private sqlconn As MySqlConnection
Private query, query1 As String
Private cmd As MySqlCommand
Private reader As MySqlDataReader
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
sqlconn = New MySqlConnection
sqlconn.ConnectionString = "server=localhost;userid=root;password='';database=innovative"
Try
sqlconn.Open()
query = "SELECT Full_Name FROM employee WHERE ID='" & txt_id_number.Text & "'"
cmd = New MySqlCommand(query, sqlconn)
reader = cmd.ExecuteReader
If reader.HasRows = False Then
MsgBox("Invalid ID number please secure that the ID number is already Exist" & vbNewLine & "TAKE NOTE:" & vbNewLine & "You cannot update or change the existing ID number for it is the primary Key for the Employee, If you want to Change it, its better to delete the Employee then add it again." & vbNewLine & "Other than that you can change the Full name, age, contact and etc.", vbCritical)
Else
query1 = "UPDATE employee SET Full_Name = #txt_fullname, Employee_Type=txt_employee_type, Age=#txt_age'"
cmd = New MySqlCommand(query1, sqlconn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#txt_fullname", SqlDbType.VarChar, 255).Value = txt_fullname.Text
cmd.Parameters.Add("#txt_employee_type", SqlDbType.VarChar, 255).Value = txt_employee_type.Text
cmd.Parameters.Add("#txt_age", SqlDbType.VarChar, 255).Value = txt_age.Text
cmd.Parameters.Add("")
cmd.ExecuteNonQuery()
MsgBox(txt_fullname.Text & " was successfully updated", vbInformation)
txt_age.Text = ""
txt_contact.Text = ""
txt_email.Text = ""
txt_employee_type.Text = ""
txt_fullname.Text = ""
txt_id_number.Text = ""
txt_status.Text = ""
cb_sex.Text = ""
add_employee()
End If
sqlconn.Close()
reader.Close()
Catch ex As Exception
Finally
sqlconn.Dispose()
End Try
End Sub
End Class
Three things to change.
Use cmd.ExecuteNonQuery for Insert or Update queries.
Do not use conn.Open again when it is not closed; It returns 'Connection is already open' error and execution will terminate to catch block. This is the reason why your code didnt work.
Parameterize the queries for security and type-casting.
Happy coding!
Here's the code of my button_click:
Private Sub Button10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button10.Click
Dim conn As New MySqlConnection
Dim cmd As New MySqlCommand
Dim dr As MySqlDataReader
conn.ConnectionString = "server = localhost; user id = root; database = db; password = root"
cmd.Connection = conn
conn.Open()
cmd.CommandText = " SELECT * FROM candidate WHERE idn = '" & TextBox4.Text & "'"
dr = cmd.ExecuteReader
If dr.HasRows Then
MessageBox.Show("Entry I.D. No. already exist", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
ElseIf TextBox4.Text = "" Or TextBox5.Text = "" Or TextBox6.Text = "" Or TextBox7.Text = "" Or ComboBox1.Text = "" Or TextBox3.Text = "" Then
MessageBox.Show("Please complete the required fields..", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else
conn.Close()
con.ConnectionString = "server = localhost; user id = root; database = db; password = root"
cmd.Connection = con
con.Open()
Dim sqlQuery As String = "INSERT INTO candidate(idn,cfname,cmname,clname,cyr,sec,vyear,votes,pword) VALUES('" & TextBox4.Text & "','" & TextBox5.Text & "','" & TextBox6.Text & "','" & TextBox7.Text & "','" & ComboBox1.Text & "','" & TextBox3.Text & "',CONCAT(YEAR(NOW()),'-',(YEAR(NOW()) + 1),'0','" & TextBox2.Text & "')"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = con
.ExecuteNonQuery()
End With
MsgBox("Record Inserted")
End If
End Sub
what's wrong with my INSERT query? I can't seem to find anything wrong here, but VB.NET says it has error in " at line 1?
"INSERT INTO candidate(vyear) VALUES(CONCAT(YEAR(NOW()),'-',(YEAR(NOW()) + 1))"
There is a unbalanced open parenthesis before the second YEAR. Need to remove it
"INSERT INTO candidate(vyear) VALUES( CONCAT(YEAR(NOW()),'-',YEAR(NOW()) + 1) )"
Looking at the updated code you really need to start to use parameterized queries
Using con = new MySqlConnection(......)
Using cmd = con.CreateCommand()
con.Open()
Dim sqlQuery As String = "INSERT INTO candidate " & _
"(idn,cfname,cmname,clname,cyr,sec,vyear,votes,pword) VALUES(" & _
"#idn, #cfname, #cmname, #clname, #cyr, #sec, " & _
"CONCAT(YEAR(NOW()),'-',YEAR(NOW()) + 1), " & _
"#votes, #pword"
With cmd
.CommandText = sqlQuery
' is idn an integer field, then pass it as integer.
' instead if it is an autoincrement then remove it and let the db calculate for you
.Parameters.AddWithValue("#idn", Convert.ToInt32(TextBox4.Text))
.Parameters.AddWithValue("#cfname, TextBox5.Text)
.... and so on for every placeholder in the parameterized text above
.ExecuteNonQuery()
End With
MsgBox("Record Inserted")
End Using
End Using