Cannot update Data in mySQL database - mysql

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!

Related

Error show if there is a duplication of record in MySQL using vb.net

Good day! Can someone help me fix my code? I would like to show an error message if there is a duplication of record. For example, I entered a username "admin" but it is already in my database so it should show a message saying "Username already exists!". Otherwise, If the username isn't used yet then it will be added in my database. I'm using Visual Studio 2005 and Navicat for MySQL
Here is my code:
conn.Open()
Dim qadd As String = "SELECT * FROM tbl_user WHERE uname='" & txt_uname.Text & "'"
Dim cmd As New MySqlCommand(qadd, conn)
Dim data As MySqlDataReader = cmd.ExecuteReader
If data.Read Then
If data(0) = txt_uname.Text Then
MsgBox("User " & data(0) & " already exists! ", MsgBoxStyle.Critical)
Else
Dim qstr As String = "INSERT INTO tbl_user (uname, pword, ulvl) VALUES ('" & txt_uname.Text & "' , '" & txt_pword1.Text & "' , '" & txt_pword2.Text & "') ON DUPLICATE KEY UPDATE uname = '" & txt_uname.Text & "'"
Dim cm As New MySqlCommand(qstr, conn)
Dim dat As MySqlDataReader = cm.ExecuteReader
MsgBox("User has been added!", MsgBoxStyle.Information)
txt_uname.Clear()
txt_pword1.Clear()
txt_pword2.Clear()
txt_uname.Focus()
End If
End If
conn.Close()
Still a lot of room for improvement, and I typed this out on my phone with no syntax checking, but think it should get you heading in the right direction. Things for you to read up on is parametrising your query/insert statements and the Using keyword which can help with managing your db connections.
Dim qadd As String = "SELECT Count(uname) FROM tbl_user WHERE uname='" & txt_uname.Text & "'"
Dim cmd As New MySqlCommand(qadd, conn)
Dim userCounter as int = cmd.ExecuteScaler
if userCounter > 0 then
MsgBox("User " & data(0) & " already exists! ", MsgBoxStyle.Critical)
Else
Dim qstr As String = "INSERT INTO tbl_user (uname, pword, ulvl) VALUES ('" & txt_uname.Text & "' , '" & txt_pword1.Text & "' , '" & txt_pword2.Text & "') ON DUPLICATE KEY UPDATE uname = '" & txt_uname.Text & "'"
Dim cm As New MySqlCommand(qstr, conn)
Dim dat As MySqlDataReader = cm.ExecuteReader
MsgBox("User has been added!", MsgBoxStyle.Information)
txt_uname.Clear()
txt_pword1.Clear()
txt_pword2.Clear()
txt_uname.Focus()
End If

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()

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

extract COUNT(column) from mySQL to VB.NET

Hey guys I have to extract some values from my DB and put them on my textbox. There's a problem at :
TextBox1.Text = TextBox1.Text & DR.Item("id") & Space(3) & DR.Item("Nume") & Space(3) & DR.Item("COUNT(pontaj.prezente)")
Error in VB:
This is how my select looks like:
Dim dbCon = New MySqlConnection("Server = localhost;Database = users; Uid=root; Pwd = password ")
'SELECT users1.id,users1.Nume, COUNT(pontaj.prezente) FROM users1, pontaj WHERE users1.id = pontaj.id
Dim strQuery = "SELECT users1.id,users1.Nume, COUNT(pontaj.prezente)" & _
"FROM users1, pontaj "
Dim SQLCmd = New MySqlCommand(strQuery, dbCon)
' Pwd = password
' Open
dbCon.Open()
Dim DR = SQLCmd.ExecuteReader
TextBox1.Text = TextBox1.Text & DR.Item("id") & Space(3) & DR.Item("Nume") & Space(3) & DR.Item("COUNT(pontaj.prezente)") & vbCrlf
While DR.Read
End While
'Close
DR.Close()
dbCon.Close()
Well, the error is clear, you cannot access the fields of a DataReader before calling Read.
The call is required to position the reader on the first record returned by the query and then to advance on the subsequent records until you reach the end of the returned records.
Also the syntax for your query seems incorrect and the way you reference the third column of your query
Dim dbCon = New MySqlConnection(............)
Dim strQuery = "SELECT users1.id,users1.Nume, COUNT(pontaj.prezente) as countPrezente " & _
"FROM users1 INNER JOIN pontaj ON users1.id = pontaj.id " & _
"GROUP BY users1.id, users1.Nume"
Dim SQLCmd = New MySqlCommand(strQuery, dbCon)
dbCon.Open()
Dim DR = SQLCmd.ExecuteReader
' If Read returns true then you have one or more record to show'
While DR.Read()
TextBox1.Text = TextBox1.Text & _
DR.Item("id") & Space(3) & _
DR.Item("Nume") & Space(3) & _
DR.Item("countPrezente") & vbCrlf
End While
DR.Close
dbCon.Close
Looking at your previous question, the Foreign Key between users1 and pontaj is named id, so I have used an explicit join between the two tables to link the records from the two tables