Update query makes the fields empty in the database - vb.net

I asked a question previously concerning updating data in a datagridview with phpMyAdmin. You can refer to it by following link -->Updating data in phpmyadmin part 1
The code works quite OK, but now the problem is that when I check for the updated data in localhost all I see are empty fields. Below is the screenshot of my vb in design. I have labelled the textboxes as per my database. The textboxes in the screenshot are set to be invisible on running my winform.
What exactly could be the problem?
#Kakarot
Here is what I initially had
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString = "server=localhost;userid=server;password=server;database=heavisa_database"
Dim rabit As MySqlDataReader
MysqlConn.Open()
Dim pin As String
pin = "UPDATE heavisa_database.new_employee SET (Employee_ID = '" & txtemployeeid.Text & "', Nat_ID = '" & txtnatid.Text & "', First_Name = '" & txtfirstname.Text & "', Middle_Name = '" & txtmiddlename.Text & "', Surname = '" & txtsurname.Text & "', NSSF_No = '" & txtnssfno.Text & "', KRA_Pin = '" & txtkrapin.Text & "', NHIF_No = '" & txtnhifno.Text & "', Residence = '" & txtresidence.Text & "', Mobile_No = '" & txtmobileno.Text & "', Email = '" & txtemail.Text & "', Job_Group = '" & cbojobgroup.Text & "', Employment_Date = '" & dtpemploymentdate.Text & "') WHERE Employee_ID = '" & txtemployeeid1.Text & "'"
Try
con = New MySqlCommand(pin, MysqlConn)
rabit = con.ExecuteReader
MessageBox.Show("Update Successful.")
MysqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
And here is what I currently have (credit goes to one Mr. ekad for it)
Dim pin As String
pin = "UPDATE heavisa_database.new_employee SET Employee_ID = #Employee_ID, Nat_ID = #Nat_ID, First_Name = #First_Name, Middle_Name = #Middle_Name, Surname = #Surname, NSSF_No = #NSSF_No, KRA_Pin = #KRA_Pin, NHIF_No = #NHIF_No, Residence = #Residence, Mobile_No = #Mobile_No, Email = #Email, Job_Group = #Job_Group, Employment_Date = #Employment_Date WHERE Employee_ID like '%{0}%'"
Try
Using MysqlConn As New MySqlConnection
MysqlConn.ConnectionString = "server=localhost;userid=server;password=server;database=heavisa_database"
MysqlConn.Open()
Using con As New MySqlCommand(pin, MysqlConn)
With con
con.Parameters.AddWithValue("#Employee_ID", txtemployeeid.Text)
con.Parameters.AddWithValue("#Nat_ID", txtnatid.Text)
con.Parameters.AddWithValue("#First_Name", txtfirstname.Text)
con.Parameters.AddWithValue("#Middle_Name", txtmiddlename.Text)
con.Parameters.AddWithValue("#Surname", txtsurname.Text)
con.Parameters.AddWithValue("#NSSF_No", txtnssfno.Text)
con.Parameters.AddWithValue("#KRA_Pin", txtkrapin.Text)
con.Parameters.AddWithValue("#NHIF_No", txtnhifno.Text)
con.Parameters.AddWithValue("#Residence", txtresidence.Text)
con.Parameters.AddWithValue("#Mobile_No", txtmobileno.Text)
con.Parameters.AddWithValue("#Email", txtemail.Text)
con.Parameters.AddWithValue("#Job_Group", cbojobgroup.Text)
con.Parameters.AddWithValue("#Employment_Date", dtpemploymentdate.Text)
End With
con.ExecuteNonQuery()
End Using
End Using
MessageBox.Show("Update Successful.")
MysqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
The first code gave me an error (refer to the link above). The second code works but it's emptying my fields instead of updating.

How did you updated your tables in your database? It should be like:
(Im gonna take my code for an old project that I did)
Private Sub disconnect()
conn.Close()
End Sub
Private Sub connect()
conn.ConnectionString = connectionString
conn.Open()
End Sub
Private Sub btnSaveEdit_Click(sender As Object, e As EventArgs) Handles btnSaveEdit.Click
connect()
Dim query as string
Dim command As New MySqlCommand
query = "Update `tblcandidates` set firstname = '" & txtEditFname.Text & "', lastname = '" & txtEditLName.Text & "', position='" & cboEditPosition.Text & "', fullname = '" & fullname & "' where recNum = '" & txtRec.Text & "'"
command.Connection = conn
command.CommandText = query
command.ExecuteNonQuery()
disconnect()
End Sub

First things first, just a simple question, is heavisa_database.new_employee a table? It's really wise to properly name them, you can put tbl before your desired name if its a table, and db before the name if its a database. Just to prevents confusions. And I think you dont need a reader when updating records in your table, correct me if I'm wrong :p
Okay, to be honest, I don't really understand much the code that Mr. ekad provided. Here's a code you can try. And oh, you don't really need the bracket after the SET.
//Global Vars
Dim connectionString As String = "server=localhost;userid=server;password=server;database=heavisa_database"
Dim conn As New MySqlConnection
First, let's make some functions for ease (you can put this anywhere in your code):
//remember that conn is our MySqlConnection
Private Sub connect()
conn.ConnectionString = connectionString
conn.Open()
End Sub
Private Sub disconnect()
conn.Close()
End Sub
So, event for your update button:
connect()
Dim pin As String
pin = "UPDATE new_employee SET Employee_ID = '" & txtemployeeid.Text & "', Nat_ID = '" & txtnatid.Text & "', First_Name = '" & txtfirstname.Text & "', Middle_Name = '" & txtmiddlename.Text & "', Surname = '" & txtsurname.Text & "', NSSF_No = '" & txtnssfno.Text & "', KRA_Pin = '" & txtkrapin.Text & "', NHIF_No = '" & txtnhifno.Text & "', Residence = '" & txtresidence.Text & "', Mobile_No = '" & txtmobileno.Text & "', Email = '" & txtemail.Text & "', Job_Group = '" & cbojobgroup.Text & "', Employment_Date = '" & dtpemploymentdate.Text & "' WHERE Employee_ID = '" & txtemployeeid1.Text & "'"
//lets create new command
Dim command As New MySqlCommand
//sets the connection for our command
command.Connection = conn
command.CommandText = pin
command.ExecuteNonQuery()
disconnect()
MessageBox.Show("Record saved!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
Try the given code above and I'm pretty sure It'll work. Goodluck!

Related

Syntax error in string in query expression in shortssize = S

Im updating an entry in MS Access using this code but it always returns an error. I dont know which part to correct. Please help me i cant seem to find which part is the error
Private Sub SaveChanges()
con.ConnectionString = OpenDBConnection()
con.Open()
Dim sql As String = "Update [JobOrderProd] set [CustomerOrderNumber] =
'" & CustomerOrderNumtxtbox.Text & "', [ItemNumber] = '" &
ItemNumbertxtbox.Text & "', [JerseyName] = '" &
JerseyNametxtbox.Text & "', [JerseyNumber] = '"`
& JerseyNumbertxtbox.Text & "', [JerseySize] = '" &
JerseySizetxtbox.Text & "',
[ShortsSize] = '" & ShortsSizetxtbox.Text
Dim cmd As New OleDbCommand(sql, con)`enter code here`
cmd.ExecuteNonQuery()`enter code here`
con.Close()
MsgBox("Entry for JO Production has been updated.")
ClearForm()
End Sub
I think you missed the single inverted comma in the end. add this to the end & "'"
JerseySizetxtbox.Text & "',
[ShortsSize] = '" & ShortsSizetxtbox.Text & "'"

How do I update multiple table column value of database using textboxes in VB.NET?

Here is my code. But It is not working on multiple update of table values, It only does work when I update a single value. please help me, im newbie here :(
Private Sub SaveChanges_Click(sender As System.Object, e As System.EventArgs) Handles SaveChanges.Click
Dim con As New MySqlConnection("host = localhost; username = root; password = 1234; database = logindb")
Dim cmd As New MySqlCommand
con.Open()
cmd.Connection = con
cmd.CommandText = "UPDATE login SET username = '" & ChangeUsername.Text & "' and password = '" & ChangePassword.Text & "' and Security_Question1 ='" & ChangeSecQue1.Text & "' and Security_Question2 = '" & ChangeSecQue2.Text & "' and Security_Answer1 = '" & ChangeSecAns1.Text & "' and Security_Answer2 = '" & ChangeSecAns2.Text & "' "
cmd.ExecuteNonQuery()
MsgBox("Saved Changes!")
con.Close()
End Sub
change your update statement:
cmd.CommandText = "UPDATE login SET username = '" & ChangeUsername.Text & "' ,password = '" & ChangePassword.Text & "' ,Security_Question1 ='" & ChangeSecQue1.Text & "' ,Security_Question2 = '" & ChangeSecQue2.Text & "' ,Security_Answer1 = '" & ChangeSecAns1.Text & "' ,Security_Answer2 = '" & ChangeSecAns2.Text & "' "

no value given for one or more required parameters in updating deleting records

I cant figure out whats wrong with this,when i update a record from my list view a pop up appears saying no value given for one or more required parameters.
heres my code:
Private Sub BtnUpdate_Click(sender As Object, e As EventArgs) Handles BtnUpdate.Click
Try
Dim SqlQuery As String = "UPDATE UsersTable Set AccountType = '" & CmbAccountType.Text & "' , Username = '" & TxtUsername.Text & "' , UserPassword = '" & TxtPassword.Text & "' , Firstname = '" & TxtFirstname.Text & "' , Lastname = '" & TxtLastname.Text & "' , Sex = '" & CmbSex.Text & "',Birthdate = '" & DateTimePickerBirthdate.Text & "' , ContactNumber = '" & TxtContact.Text & "' , Address = '" & TxtAddress.Text & "' WHERE UserID = " & id & ";"
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = Conn
.ExecuteNonQuery()
End With
MsgBox("Account successfully updated!")
loadlistview()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub BtnDelete_Click(sender As Object, e As EventArgs) Handles BtnDelete.Click
Try
Dim SqlQuery As String = "DELETE FROM ProductTable WHERE UserID = " & id & ";"
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = Conn
.ExecuteNonQuery()
End With
MsgBox("Account deleted.")
loadlistview()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
The problem is in the WHERE condition which you used in your query. so you can correct it by using the following query
In update query :
Dim SqlQuery As String = "UPDATE UsersTable Set AccountType = '" & CmbAccountType.Text & "'....................." & _
"WHERE UserID = '" & id & "';" '<----- you miss a single quote in where clause.
In Delete query :
Dim SqlQuery As String = "DELETE FROM ProductTable WHERE UserID = '" & id & "';"

updating a sql 2005 database using text boxes in vb.net

I have a VB.Net form which allows the user to update the customer details such as name, contact no:, etc. So when the customer enters the new name for the customer name etc. the application should update the corresponding field in the existing entry that relates to the customer ID.
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim adapter As New SqlDataAdapter
Dim dt As New DataTable
cn.ConnectionString = ("Data Source=NIMO-HP\SQLEXPRESS;Initial Catalog=FYP_db;Integrated Security=True")
cmd.Connection = cn
cn.Open()
cmd.CommandText = " UPDATE TblCustomerDetails (compID, compName, compContact, compAddress, compFax, compEmail, compPayterm, compTaxscheme, compPaymode, compRemarks ) SET Values ('" & lblCID.Text & "', '" & txtCname.Text & "', '" & txtCpno.Text & "', '" & txtCaddrs.Text & "','" & txtCfax.Text & "', '" & txtCemail.Text & "', '" & cmbPterm.Text & "','" & cmbTaxschm.Text & "',' " & cmbPmode.Text & "', '" & txtRemarks.Text & "') WHERE compID = '" & lblCID.Text & "';"
cmd.ExecuteNonQuery()
MsgBox("Account updated!!", MsgBoxStyle.Information, "Updation complete")
Your using a INSERT syntax for your UPDATE statement. Your UPDATE statement should have the form:
UPDATE tableName
SET col1 = val1,
col2 = val2,
col3 = val3
WHERE someColumn = someValue
Additionally, you are wide open to SQL Injection attacks by using non-parameterized queries. Finally, I would use a Using blocks to ensure your connection and command are properly closed and disposed of.
Putting it all together it would look something like this:
Using Dim cn As SqlConnection = New SqlConnection("Data Source=NIMO-HP\SQLEXPRESS;Initial Catalog=FYP_db;Integrated Security=True")
cn.Open()
Dim sqlQuery As String = "UPDATE TblCustomerDetails " + _
"SET compName = #compName, " + _
"compContact = #compContact, " + _
"compAddress = #compAddress, " + _
"compFax = #compFax, " + _
"compEmail = #compEmail, " + _
"compPayterm = #compPayterm, " + _
"compTaxscheme = #compTaxscheme, " + _
"compPaymode = #compPaymode, " + _
"compRemarks = #compRemarks " + _
"WHERE compID = #compID"
Using Dim cmd As SqlCommand = New SqlCommand(sqlQuery, cn)
cmd.Parameters.AddWithValue("#compFax", txtCname.Text)
cmd.Parameters.AddWithValue("#compContact", txtCpno.Text)
cmd.Parameters.AddWithValue("#compAddress", txtCaddrs.Text)
cmd.Parameters.AddWithValue("#compFax", txtCfax.Text)
cmd.Parameters.AddWithValue("#compEmail", txtCemail.Text)
cmd.Parameters.AddWithValue("#compPayterm", cmbPTerm.Text)
cmd.Parameters.AddWithValue("#compTaxscheme", cmbTaxschm.Text)
cmd.Parameters.AddWithValue("#compPaymode", cmbPmode.Text)
cmd.Parameters.AddWithValue("#compRemarks", txtRemarks.Text)
cmd.Parameters.AddWithValue("#compID", lblCID.Text)
Dim result As Integer
result = cmd.ExecuteNonQuery()
If result = 1 Then
MsgBox("Account updated!!", MsgBoxStyle.Information, _
"Updation complete")
Else
MsgBox("Account not updated!!", MsgBoxStyle.Information, _
"Updation not complete")
End If
End Using
End Using
There are a few more things to note in the above code sample:
First, I removed compID from the list of values to update. You're using that in your WHERE query, so I think you would have interesting results in your query if you're trying to update the same column you are using as part of your WHERE clause. Additionally, the source for that value is a Label, which tells me it's not supposed to be changed.
Secondly, ExecuteNonQuery() returns an int with the number of rows affected. In this case, it should be 1 - if it's not 1, I have you show a different message box.
Thirdly, cmbPTerm, cmbTaxxshm and cmbPmode sound like ComboBox to me, and you're not going to get what I think you're expecting using their Text property. I think you'll want SelectedText - hard to say without knowning how your ComboBoxes are bound. I'll leave that as an exercise for you :)
Fourth, I broke the UPDATE query up across several lines simply for readability - you don't have to do it that way, as long as the query is correct.
Finally, I'd suggest using MessagBox.Show() vs MsgBox.
Dim cnn As New SqlConnection
Dim cmd As New SqlCommand
cnn.ConnectionString = ("Data Source=NIMO-HP\SQLEXPRESS;Initial Catalog=FYP_db;Integrated Security=True")
cmd.Connection = cnn
cnn.Open()
cmd.CommandText = "update TblCustomerDetails set compName='" & txtCname.Text & "' , compContact = '" & txtCpno.Text & "' , compAddress = '" & txtCaddrs.Text & "' , compFax = '" & txtCfax.Text & "' , compEmail = '" & txtCemail.Text & "' , compPayterm = '" & cmbPterm.Text & "' , compTaxscheme = '" & cmbTaxschm.Text & "' , compPaymode = '" & cmbPmode.Text & "' , compRemarks = '" & txtRemarks.Text & "' where compID = '" & lblCID.Text & "'"
cmd.ExecuteNonQuery()
cnn.Close()
MessageBox.Show("entry updated!!!")

how to refresh datagrid and update database?

i have some trobles in updating my database. ihave this codes :
Dim cmd As OleDbCommand
Dim sql As String
sql = "UPDATE nmat SET nip = '" & lblNipDosen.Text & "', nim = '" & TxtNIM.Text & "', ntugas = '" & TxtNtugas.Text & "', nabsensi = '" & TxtNabsen.Text & "', nuts = '" & TxtNuts.Text & "', nuas = '" & TxtNuas.Text & "' WHERE nim='" & TxtNIM.Text & "'"
conn.Open()
Dim reader As OleDbDataReader
Try
cmd = New OleDbCommand(sql, conn)
cmd.ExecuteNonQuery()
DataGridView1.Refresh()
Finally
'reader.Close()
End Try
conn.Close()
my problem is, by these code, the grid can be refreshed after i close and open this form again. but if i check in my ms Access, the data was not chanded at all. how to update my database and showed in my datagrid??
Try This :
Dim cmd As OleDbCommand
Dim rstTable As New DataTable()
Dim sql As String
sql = "UPDATE nmat SET nip = '" & lblNipDosen.Text & "', nim = '" & TxtNIM.Text & "', ntugas = '" & TxtNtugas.Text & "', nabsensi = '" & TxtNabsen.Text & "', nuts = '" & TxtNuts.Text & "', nuas = '" & TxtNuas.Text & "' WHERE nim='" & TxtNIM.Text & "'"
conn.Open()
Dim reader As OleDbDataReader
Try
cmd = New OleDbCommand(sql, conn)
rstTable.Load(cmd.ExecuteReader())
DataGridView1.DataSource =rstTable
Finally
'reader.Close()
End Try
conn.Close()
your gridview columns should have bound to a field