MySQL Syntax Error in VB.NET - mysql

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

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

INSERT INTO in MySQL not working but no errors?

I somehow can't insert data into my MySQL database but I know there's no trouble with the query cause there is no error message and it can make it as far as the Success message box. I think the query is right for MySQL but it is not the specific one that I should use for INSERT INTO.
Here's my code:
Imports MySql.Data.MySqlClient
Public Class Register
Dim ServerString As String = "Server=localhost; UserId =root; Password = ; Database = gym;"
Dim MysqlConn As MySqlConnection = New MySqlConnection
Dim COMMAND As MySqlCommand
Dim password, pass As String
Dim member As Integer
Private Sub Register_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.CenterToParent()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MysqlConn.ConnectionString = ServerString
Dim READER As MySqlDataReader
password = TextBox2.Text
pass = TextBox3.Text
confirm(password, pass)
If TextBox1.Text = Nothing Or TextBox2.Text = Nothing Or TextBox3.Text = Nothing Or TextBox4.Text = Nothing Or TextBox5.Text = Nothing Or TextBox6.Text = Nothing Or DateTimePicker1.Text = Nothing Or RadioButton1.Checked = False And RadioButton2.Checked = False Then
MsgBox("Please Fill your Information Completely")
Else
MysqlConn.ConnectionString = ServerString
Try
MysqlConn.Open()
Dim query As String
query = "select * from gym.user where user_name ='" & TextBox1.Text & "'"
COMMAND = New MySqlCommand(query, MysqlConn)
READER = COMMAND.ExecuteReader
Dim count As Integer
While READER.Read
count = count + 1
End While
MysqlConn.Close()
If count > 0 Then
MsgBox("User Already Exists")
Else
MysqlConn.Open()
query = "INSERT INTO gym.user(user_name,user_password,user_firstname,user_lastname,user_birthday,user_contact,user_membership) VALUES ('" & TextBox1.Text & "', md5('" & TextBox2.Text & "') ,'" & TextBox4.Text & "','" & TextBox5.Text & "','" & DateTimePicker1.Value.Date & "','" & TextBox6.Text & "','" & member & "')"
COMMAND = New MySqlCommand(query, MysqlConn)
MsgBox("USER REGISTERED")
MysqlConn.Close()
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
MysqlConn.Dispose()
End Try
End If
End Sub
You're missing ExecuteNonQuery statement:
query = "INSERT INTO gym.user(user_name,user_password,user_firstname,user_lastname,user_birthday,user_contact,user_membership) VALUES ('" & TextBox1.Text & "', md5('" & TextBox2.Text & "') ,'" & TextBox4.Text & "','" & TextBox5.Text & "','" & DateTimePicker1.Value.Date & "','" & TextBox6.Text & "','" & member & "')"
COMMAND = New MySqlCommand(query, MysqlConn)
COMMAND.ExecuteNonQuery()

Cannot update Data in mySQL database

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!

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

how to search and update record mysql in vb

i have problem to search and update record database sql.
this is my code. i using mysql database and Microsoft Visual Basic 2008
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim t As New Threading.Thread(AddressOf closeMsgbox)
objconn = New MySqlConnection("server=localhost;database=AAA;userid=root;password= 'root'")
Dim username As Boolean = True
objconn.Open()
Dim sqlquery As String = "SELECT * FROM daftar WHERE nid = '" & FormRegister.TextBox1.Text & "';"
Dim data As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = sqlquery
command.Connection = objconn
adapter.SelectCommand = command
data = command.ExecuteReader
If data.HasRows() = True Then
While data.Read()
FormRegister.Show()
tkhupd = Now.ToString("yyyy-MM-dd HH:mm:ss")
command.Connection = objconn
command.CommandText = "UPDATE visitor SET tkhupd ='" & tkhupd & "' WHERE nokp = '" & FormRegister.TextBox1.Text & "';"
command.ExecuteNonQuery()
MessageBox.Show("You're has logout")
FormRegister.TextBox1.Text = ""
username = False
Me.Close()
End While
Else
FormRegister.Show()
username = True
End If
data.Close()
If username = True Then
Dim sqlquery2 As String = "INSERT INTO visitor (nid)VALUES ('" & FormRegister.TextBox1.Text & "')"
Dim data2 As MySqlDataReader
Dim adapter2 As New MySqlDataAdapter
Dim command2 As New MySqlCommand
command2.CommandText = sqlquery2
command2.Connection = objconn
adapter2.SelectCommand = command2
data2 = command2.ExecuteReader
MessageBox.Show("You're has login")
Form4.Show()
FormRegister.TextBox1.Text = ""
Me.Close()
End If
End Sub
but i have error on Word command.ExecuteNonQuery(): MySqlException was unhandled. There is already an open DataReader associated with this Connection which must be closed first
You need to use a separate MySqlCommand object, say command2 inside your While statement , because command is already in active use:
Dim command2 As New MySqlCommand
..
While data.Read()
..
command2.Connection = objconn
..
End While
I would do this all in one call to the database, comprising two statements. I'm more used to Sql Server, so this syntax may be a little off, but it would look something like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sqlquery As String = _
"DECLARE #RowCount Int;" & _
" UPDATE FROM visitor v" & _
" INNER JOIN daftar d ON d.nid = v.nokp" & _
" SET v.tkhupd = current_timestamp" & _
" WHERE d.nid = ?NID;" & _
" SELECT row_count() INTO #RowCount;" & _
" IF #RowCount = 0 THEN " & vbCrLf & _
" INSERT INTO visitor (nid) VALUES (?NID);" & vbCrLf & _
" END IF"
Using conn As New MySqlConnection("server=localhost;database=AAA;userid=root;password= 'root'"), _
cmd As New MySqlCommand(sqlquery, conn)
cmd.Parameters.Add("?NID", MySqlDbTypes.Int).Value = Integer.Parse(FormRegister.TextBox1.Text)
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub