this is my code that inputs a record for my database. if I put a duplicate it will just terminate the program. my goal is to put a message box that displays an error so that the program will not terminate.
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
MysqlConn = New MySqlConnection("server=localhost; user=root; pwd=; database=payrollmanagement")
MysqlConn.Open()
command = New MySqlCommand("INSERT INTO emp_info(empID,lastname,firstname,MiddleInitial,Age,address,Position,ContactNumber,pay_type,gender,dept,email) Values ('" & TextBox1.Text & "','" & TextBox5.Text & "','" & TextBox6.Text & "','" & TextBox7.Text & "','" & TextBox11.Text & "','" & TextBox3.Text & "','" & TextBox10.Text & "','" & TextBox4.Text & "','" & TextBox8.Text & "','" & TextBox10.Text & "','" & TextBox2.Text & "','" & TextBox14.Text & "')", MysqlConn)
If (TextBox1.Text = "") Then
MessageBox.Show("Data not Inserted")
ElseIf (TextBox2.Text = "") Then
MessageBox.Show("Data not Inserted")
ElseIf (TextBox3.Text = "") Then
MessageBox.Show("Data not Inserted")
ElseIf (TextBox4.Text = "") Then
MessageBox.Show("Data not Inserted")
ElseIf (TextBox5.Text = "") Then
MessageBox.Show("Data not Inserted")
ElseIf (TextBox6.Text = "") Then
MessageBox.Show("Data not Inserted")
ElseIf (TextBox7.Text = "") Then
MessageBox.Show("Data not Inserted")
ElseIf (TextBox8.Text = "") Then
MessageBox.Show("Data not Inserted")
ElseIf (TextBox9.Text = "") Then
MessageBox.Show("Data not Inserted")
ElseIf (TextBox10.Text = "") Then
MessageBox.Show("Data not Inserted")
ElseIf (TextBox11.Text = "") Then
MessageBox.Show("Data not Inserted")
ElseIf (TextBox14.Text = "") Then
MessageBox.Show("Data not Inserted")
Else
command.ExecuteNonQuery()
MessageBox.Show("Data Inserted")
Shadows_load()
End If
End Sub
Add a MySqlDataReader class so that the program can read if there is any existing data in the database
MysqlConn = New MySqlConnection("//YourConnection")
MysqlConn.Open()
command = New MySqlCommand("//Your sql")
MySqlDataReader reader;
reader = command.ExecuteReader()
If reader.Read() = true Then 'This will solve your problem
MessageBox.Show("There is already existing data.")
Else
If (TextBox1.Text = "") Then
MessageBox.Show("Data not Inserted")
...
Else
command.ExecuteNonQuery()
MessageBox.Show("Data Inserted")
Shadows_load()
End If
End If
If all textboxes are used to insert data, you can loop through textboxes to add error message boxes.
For Each c As Control In Controls
If TypeOf c Is TextBox Then
If c.Text = "" Then
MessageBox.Show("Data not Inserted")
End If
End If
Next
You can also use 'Tag' or 'TabIndex' property to identify each textbox.
First the validation code is run and if it is OK then attempt to insert the new user. The Insert statement will only add the user if the id does not exist.
Private Function ValidateInput() As Boolean
For Each tb In Controls.OfType(Of TextBox)
If tb.Text = "" Then
MessageBox.Show("Data not Inserted")
tb.Focus()
Return False
End If
Next
Return True
End Function
Private Function InsertUser(id As String, lname As String, fname As String, middle As String) As Integer
Dim sql = "INSERT INTO dbusers (empID, lastname, firstname, MiddleInitial)
Select #ID, #LName, #FName #MiddleIn
WHERE Not EXISTS
(SELECT * FROM dbusers WHERE empID = #ID);"
Dim RetVal As Integer
Using cn As New MySqlConnection("server=localhost; user=root; pwd=; database=payrollmanagement"),
cmd As New MySqlCommand(sql, cn)
With cmd.Parameters
.Add("#Id", MySqlDbType.VarChar).Value = id
.Add("#LName", MySqlDbType.VarChar).Value = lname
.Add("#FName", MySqlDbType.VarChar).Value = fname
.Add("#MiddleInitial", MySqlDbType.VarChar).Value = middle
End With
cn.Open()
RetVal = cmd.ExecuteNonQuery()
End Using
Return RetVal
End Function
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
If ValidateInput() Then
Dim RowsEffected = InsertUser(TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text)
If RowsEffected = 1 Then
MessageBox.Show("Successful insert.")
Else
MessageBox.Show("Error with insert.")
End If
End If
End Sub
Related
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
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
Private Sub btnAddNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveBtn.Click
'Try
If Not IsNumeric(txtUnit.Text) Then
MsgBox("Enter Unit Number.", MsgBoxStyle.Critical, "LASAC")
Exit Sub
ElseIf txtName.Text = "" Then
MsgBox("Enter Name.", MsgBoxStyle.Critical, "LASAC")
Exit Sub
End If
If DataGridView1.SelectedRows.Count = 0 Then
conn.ConnectionString = constring
conn.Open()
sSQL = "INSERT INTO tblBilling(Unit,FullName) VALUES(" & CInt(txtUnit.Text) & ",'" & Replace(txtName.Text, "'", "''") & "')"
cmd = New OleDbCommand(sSQL, conn)
cmd.ExecuteReader()
conn.Close()
MsgBox("Sucessfully added", MsgBoxStyle.Information, "New")
NewBtn.PerformClick()
Else
conn.ConnectionString = constring
conn.Open()
sSQL = "UPDATE tblBilling SET FullName = '" & Replace(txtName.Text, "'", "''") & "', Unit = " & CInt(txtUnit.Text) & " WHERE 'ID = '" & DataGridView1.SelectedRows(0).Cells(0).Value & ""
cmd = New OleDbCommand(sSQL, conn)
cmd.ExecuteReader()
conn.Close()
MsgBox("Successfully Updated", MsgBoxStyle.Information, "Update")
End If
DataGridView1.Rows.Clear()
showmember()
txtName.Enabled = False
txtUnit.Enabled = False
'Catch ex As Exception
' MsgBox(ex.Message, MsgBoxStyle.Critical, "Save")
'End Try
End Sub
Private Sub NewBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewBtn.Click
txtName.clear()
txtUnit.Clear()
txtUnit.Enabled = True
txtName.Enabled = True
DataGridView1.ClearSelection()
End Sub
Private Sub DeleteBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeleteBtn.Click
If DataGridView1.SelectedRows.Count <> 0 Then
If MsgBox("You are deleting a confidential data?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Statement Deleting") = MsgBoxResult.Yes Then
conn.ConnectionString = constring
conn.Open()
'MsgBox(DataGridView1.SelectedRows(0).Cells(0).Value)
sSQL = "DELETE FROM tblBilling WHERE ID = " & DataGridView1.SelectedRows(0).Cells(0).Value & ""
cmd = New OleDbCommand(sSQL, conn)
cmd.ExecuteReader()
conn.Close()
'MsgBox("Data successfully delete", MsgBoxStyle.Information, "DELETE")
DataGridView1.Rows.RemoveAt(DataGridView1.SelectedRows(0).Index)
NewBtn.PerformClick()
'Else
' MsgBox("Delete Canceled")
End If
End If
showmember()
txtName.Enabled = False
txtUnit.Enabled = False
End Sub
You have a code to clear all your rows, but didn't to retrieve the data bank
Else
conn.ConnectionString = constring
conn.Open()
sSQL = "UPDATE tblBilling SET FullName = '" & Replace(txtName.Text, "'", "''") & "', Unit = " & CInt(txtUnit.Text) & " WHERE 'ID = '" & DataGridView1.SelectedRows(0).Cells(0).Value & ""
cmd = New OleDbCommand(sSQL, conn)
cmd.ExecuteReader()
conn.Close()
MsgBox("Successfully Updated", MsgBoxStyle.Information, "Update")
End If
' you have clear all your rows here
DataGridView1.Rows.Clear()
showmember()
txtName.Enabled = False
txtUnit.Enabled = False
'Catch ex As Exception
' MsgBox(ex.Message, MsgBoxStyle.Critical, "Save")
'End Try
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