VB.NET: Too many connections - mysql

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

Related

VB.net connect to database pop out 'Truncated incorrect DOUBLE value: 'System.Windows.Forms.TextBox, Text: 1''

I was using vb.net and try to update the row of the sourcedata in the gridview which connected to the database.I'm using primary key id in the database.
Below is the related code,This is to generate the primary key ID:
Private Sub GetId()
Dim Id As Integer
Dim query As String
Dim nameid As Integer
query = "select Id from information.information order by Id Desc"
sqlConn.ConnectionString = "server =" + server + ";" + "user id=" + username + ";" _
+ "password=" + password + ";" + "database = " + database
sqlConn.Open()
sqlCmd = New MySqlCommand(query, sqlConn)
sqlRd = sqlCmd.ExecuteReader()
If (sqlRd.Read()) Then
nameid = Integer.Parse(sqlRd(0)) + 1
Id = nameid.ToString("00")
ElseIf (Convert.IsDBNull(sqlRd)) Then
Id = ("01")
Else
Id = ("01")
End If
sqlConn.Close()
txtId.Text = Id
End Sub
This is to update the rows:
Private Sub Editrow()
sqlConn.ConnectionString = "server =" + server + ";" + "user id=" + username + ";" _
+ "password=" + password + ";" + "database = " + database
sqlConn.Open()
sqlCmd.Connection = sqlConn
With sqlCmd
.CommandText = "Update information.information set Name=#Name,EmailAddress=#EmailAddress,PhoneNumber=#PhoneNumber,DOB=#DOB,Address=#Address where Id=#newId"
.CommandType = CommandType.Text
.Parameters.AddWithValue("#newId", txtId)
.Parameters.AddWithValue("#Name", txtName)
.Parameters.AddWithValue("#EmailAddress", txtEmailAddress)
.Parameters.AddWithValue("#PhoneNumber", txtPhoneNumber)
.Parameters.AddWithValue("#DOB", txtDob)
.Parameters.AddWithValue("#Address", txtAddress)
End With
sqlCmd.ExecuteNonQuery()
sqlConn.Close()
updateTable()
'clear txtbox values
txtId.Text = ""
txtName.Text = ""
txtEmailAddress.Text = ""
txtPhoneNumber.Text = ""
txtDob.Text = ""
txtAddress.Text = ""
End Sub
this is to get the rows:
Private Sub Getrow()
Try
txtId.Text = DataGridView1.SelectedRows(0).Cells(0).Value.ToString()
txtName.Text = DataGridView1.SelectedRows(0).Cells(1).Value
txtEmailAddress.Text = DataGridView1.SelectedRows(0).Cells(2).Value
txtPhoneNumber.Text = DataGridView1.SelectedRows(0).Cells(3).Value
txtDob.Text = DataGridView1.SelectedRows(0).Cells(4).Value
txtAddress.Text = DataGridView1.SelectedRows(0).Cells(5).Value
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
And here is the error:
error message
here is my database setting:
database
I am making the following assumption: txtId, txtName, txtEmailAddress, etc. are textboxes on a form.
In your code you currently are passing the Textbox object. I think if you pass the Text property of your textbox (ie txtName.Text) instead it will fix your issue.
With sqlCmd
.CommandText = "Update information.information set Name=#Name,EmailAddress=#EmailAddress,PhoneNumber=#PhoneNumber,DOB=#DOB,Address=#Address where Id=#newId"
.CommandType = CommandType.Text
.Parameters.AddWithValue("#newId", txtId.Text)
.Parameters.AddWithValue("#Name", txtName.Text)
.Parameters.AddWithValue("#EmailAddress", txtEmailAddress.Text)
.Parameters.AddWithValue("#PhoneNumber", txtPhoneNumber.Text)
.Parameters.AddWithValue("#DOB", txtDob.Text)
.Parameters.AddWithValue("#Address", txtAddress.Text)
End With

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

Reading data from excel merge cells using vb.net

I'm new to vb.net and I'm creating thesis project in our school. I want to fetch data from my excel file where cells was merge and it keeps on popping conversion from type 'Range' to type 'String' is not valid. Here's my code that I copied and credits for them:
Try
con.Open()
workbook = app.Workbooks.Open(fileOpener.SelectedPath + "\ahrmt.xlsx")
worksheet = workbook.Worksheets("Sheet1")
curbook = 0
Me.Text = String.Format("{0:F0}%", ((curbook / books) * 100)) + " of records has been imported."
Dim cmd As New MySqlCommand
Dim maxrow As Integer = 9
Dim noRecs, AYear As Integer
Dim semester, course As String
Me.lblWait.Visible = True
'=====================================
Dim str As String
str = worksheet.Range("A6").Text
If str.Contains("FIRST SEMESTER") = True Then
semester = "First Semester"
Else
semester = "Second Semester"
End If
Dim exAY = Regex.Replace(worksheet.Cells(6, 1), "\D", "")
AYear = exAY
Dim AcadY As New System.Text.StringBuilder()
For i As Integer = 0 To exAY.Length - 1
AcadY.Append(exAY(i))
If i Mod 4 = 3 AndAlso i > 0 AndAlso i < exAY.Length - 1 Then
AcadY.Append(" - ")
End If
Next
course = "Associate in Hotel and Restaurant Management Technology"
'=======================================
'--------to get the total rows
For x As Integer = 9 To worksheet.Rows.Count
If worksheet.Cells(x, 2).Value = Nothing Then
Exit For
Else
maxrow += 1
End If
Next
'----------for inserting records
For i As Integer = 9 To worksheet.Rows.Count
If worksheet.Cells(i, 2).Value = Nothing Then
Exit For
Else
Me.ProgressBar1.Visible = True
Me.ProgressBar1.Value += 1
Me.ProgressBar1.Maximum = maxrow - 9
Me.lblImport.Text = String.Format("{0:F0}%", ((ProgressBar1.Value / ProgressBar1.Maximum) * 100))
cmd.Connection = con
cmd.CommandText = "INSERT INTO tblsif(IDNo, Status, FName, MName, LName, Gender, YearLevel, Semester, AcadYear, PresCourse) " & _
"VALUES('" & worksheet.Cells(i, 2).Value & "','" & enrolledStat & "','" & worksheet.Cells(i, 5).Value & "','" & worksheet.Cells(i, 6).Value & "'," & _
"'" & worksheet.Cells(i, 4).Value & "','" & worksheet.Cells(i, 10).Value & "','" & worksheet.Cells(i, 1).Value & "','" & semester & "','" & AcadY & "','" & course.ToString & "')"
cmd.ExecuteNonQuery()
noRecs += 1
Me.lblTotalRec.Text = "Importing " + noRecs.ToString + " records from AHRMT Course."
End If
Next
'workbook.Save()
workbook.Close()
app.Quit()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Me.ProgressBar1.Value = 0
Me.ProgressBar1.Visible = False
Me.lblTotalRec.Text = Nothing
Me.lblImport.Text = Nothing
con.Dispose()
con.Close()
curbook = 1
Me.Text = String.Format("{0:F0}%", ((curbook / books) * 100)) + " of records has been imported."
Hope you can help me.

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

Select Value then Insert To Mysql

I'm trying to insert a value from a selected value. If the row fetched is equal to 1 or greater than 0 then It will insert the data to another table.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' Try
con.Open()
sql = "SELECT user_id, username, password FROM tbl_user WHERE username = '" & txt_user.Text & "' AND password= '" & txt_pass.Text & "' IS NOT NULL"
cmd = New MySqlCommand(sql, con)
dr = cmd.ExecuteReader
While dr.Read
txt_user.Text = dr("username")
txt_pass.Text = dr("password")
Main.Show()
Me.Hide()
ctr += 1
End While
If ctr = 0 Then
MsgBox("Login Failed!")
txt_user.Clear()
txt_pass.Clear()
Else
sql = "INSERT INTO user_log(user_id, username, log_datetime)VALUES(" & dr(0) & ",'" & dr(1) & "','" & DateTime.Today & "')"
cmd2 = New MySqlCommand(sql, con)
cmd2.ExecuteNonQuery()
End If
dr.Close()
cmd.Dispose()
con.Close()
' Catch ex As Exception
' End Try
End Sub