Try and catch in MysqlCmd.ExecuteNonQuery in insert MySQL - mysql

When I insert a null it shows an error in my code. Can I try and catch it? I don't know how.
Call Connects()
MySqlCmd = New MySqlCommand
MySqlCmd.Connection = Myconnect
MySqlCmd.CommandText = "Select ID,ItemName,Quantity,ItemDesc,SuppInfo,datee from item "
MyDA = New MySqlDataAdapter
myDataTable = New DataTable
MyDA.SelectCommand = MySqlCmd
MyDA.Fill(myDataTable)
MySqlCmd = New MySqlCommand
MySqlCmd.Connection = Myconnect
MySqlCmd.CommandText = "INSERT INTO item(ID,ItemName,Quantity,ItemDesc,SuppInfo,Po_Number,datee) VALUES('" & TextBox7.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "','" & TextBox6.Text & "',CURRENT_TIMESTAMP)"
MySqlCmd.ExecuteNonQuery()
MsgBox("New working", MsgBoxStyle.Information)
Is there anything I can do?
Here is a screenshot which shows the error:

Check your value of TextBox3.Text and if it cannot be parsed to int, replace it with 0. If you want insert NULL specify it precisely, not with empty string.

If Label30.Text = 1 Then
Try
If TextBox7.Text = "" Or TextBox2.Text = "" Or TextBox3.Text = "" Or TextBox4.Text = "" Or TextBox5.Text = "" Or TextBox6.Text = "" Then
MessageBox.Show("ERROR!")
ElseIf TextBox7.TextLength > 0 And TextBox2.TextLength > 0 And TextBox3.TextLength > 0 And TextBox4.TextLength > 0 And TextBox5.TextLength > 0 And TextBox6.TextLength > 0 Then
Call Connects()
MySqlCmd = New MySqlCommand
MySqlCmd.Connection = Myconnect
MySqlCmd.CommandText = "Select ID,ItemName,Quantity,ItemDesc,SuppInfo,datee from item "
MyDA = New MySqlDataAdapter
myDataTable = New DataTable
MyDA.SelectCommand = MySqlCmd
MyDA.Fill(myDataTable)
its working now thankyou :) this is how i solve my own problem.

Related

How do i fix an error for an unhandled exception?

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

VB.NET: Too many connections

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

vb.net data connection with mysql

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

How to get a value from Database MySQL without Events in my Form Vb Net

i have a problem to get value idsiswa from my database without any events on my form,
It is my Code :
GetIdNilai = {DRnilai.Item("idsiswa")}
StrSQL = "SELECT * from nilai WHERE idsiswa = '" & GetIdNilai.ToString & "' and kodepelajaran = '" & KODEPEL & "' AND semester='" & cSEMESTER & "' AND tahun = '" & THNPEL & "' AND kodeulangan='" & KODEUL & "' order by idsiswa "
CMDSiswa.CommandText = StrSQL
DRsiswa = CMDSiswa.ExecuteReader()
DataGridView1.Rows.Clear()
While DRsiswa.Read
NOMOR = NOMOR + 1
DATA = {NOMOR.ToString, DRsiswa.Item("idsiswa"), DRsiswa.Item("nama"), 0, cSEMESTER, THNPEL}
DataGridView1.Rows.Add(DATA)
End While
It's not working, thanks before
This will be much simpler if you just bind to the datasource. Also, never ever EVER use string concatenation like that to build your queries. This code below demonstrates how to handle both issues:
GetIdNilai = {DRnilai.Item("idsiswa")}
StrSQL = _
"SELECT idsiswa, nama, 0, #Semester, #THNPEL" &
"FROM nilai " &
"WHERE idsiswa = #IDNilai AND kodepelajaran = #KODEPEL " &
" AND semester = #Semester AND tahun = #THNPEL AND kodeulangan = #KODEUL " &
"ORDER BY idsiswa"
CMDSiswa.CommandText = StrSQL
'I'm guessing at parameter types here. Use the actual column types and lengths from your database
CMDSiswa.Parameters.Add("#IDNilai", MySqlDbtype.Int32).Value = CInt(GetIdNilai)
CMDSiswa.Parameters.Add("#KODEPEL", MySqlDbType.VarChar, 50).Value = KODEPEL
CMDSiswa.Parameters.Add("#Semester", MySqlDbType.VarChar, 1).Value = cSEMESTER
CMDSiswa.Parameters.Add("#THNPEL", MySqlDbType.VarChar, 50).Value = THNPEL
CMDSiswa.Parameters.Add("#KODEUL", MySqlDbType.VarChar, 2).Value = KODEUL
DRsiswa = CMDSiswa.ExecuteReader()
DataGridView1.DataSource = DRsiswa

MySQL Syntax Error in VB.NET

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