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!!!")
Related
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 & "' "
Wondering if someone can help me with this please. I'm getting the following error message when adding data to an access database.I know it's a time issue function but I don't know how to fix it so I can add data to the database in the required format. One or more values are prohibited by the validation rule 'Time()' set for 'tblmph'. Enter a value that the expression for this field can accept.
Public Sub Add_Data()
con.Open()
Dim rs As New OleDb.OleDbCommand("Insert into tblmph(ID,ThisDate,TimeStart,TimeFinish,Notes) " _
& "values ('" & TextBox1.Text & "' , '" & TextBox2.Text & "' , '" & TextBox3.Text & "' , '" _
& TextBox4.Text & "', '" & TextBox5.Text & "')", con)
rs.ExecuteNonQuery()
con.Close()
Display_Data()
End Sub
The columns are formatted as follows
ID = Auto Number-Long Integer
ThisDate = Short Date
TimeStart = Medium Time, Default Value = Time()
TimeFinish = Medium Time, Default Value = Time()
Notes = Memo
Do not insert the value of ID. If it is truly an auto-number, Access will automatically assign a value to the newly inserted row. Trying to insert a value into the field will cause an error and prevent the insert from working.
Change your Dim statement to:
Dim rs As New OleDb.OleDbCommand( "Insert into tblmph( ThisDate, TimeStart, TimeFinish, Notes ) values ( '" & TextBox2.Text & "' , '" & TextBox3.Text & "' , '" & TextBox4.Text & "', '" & TextBox5.Text & "' ) ", con)
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!
i have a textbox named AddU.text, i also have a msaccess table field named Quantity, what I want is that when i input a value in AddU.Text and click the add button, the value i entered will be automatically add to the existing value in Quantity. I keep searching for solution but can't find the right one. Can anyone help me? Heres my current codes:
Dim cmd As New OleDb.OleDbCommand
If Not conn.State = ConnectionState.Open Then
conn.Open()
End If
Try
cmd.Connection = conn
cmd.CommandText = "UPDATE BC_Inventory SET [Addition]='" + AddU.Text + "'," + _
"[Date_Updated]='" + DateU.Text + "',[Time_Updated]='" + TimeU.Text + "',[Updated_By]='" + UpdatedBy.Text + "'" + _
"WHERE [Item]='" + com_ItemU.Text + "'"
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error")
Finally
conn.Close()
End Try
actually i still have no codes for it, i keep trying the codes i found in researching but nothing helps thats why i deleted it.
I suspect that your quantity-field is a field in your table?
This is the changed SQL-Query.
Dim cmd As New OleDb.OleDbCommand
If Not conn.State = ConnectionState.Open Then
conn.Open()
End If
Try
' SQL-Query with Database Update on Field Quantity = Quantity + AddU.Text
Dim strSQL As String = "" & _
"UPDATE BC_Inventory " & _
"SET [Addition] = '" & AddU.Text & "', " & _
" [Quantity] = CDbl([Quantity]) + CDbl(" & CDbl(AddU.Text.Replace(",", ".")) & "), " & _
" [Date_Updated] = '" & DateU.Text & "', " & _
" [Time_Updated] = '" & TimeU.Text & "', " & _
" [Updated_By] = '" & UpdatedBy.Text & "' " & _
"WHERE [Item] = '" & com_ItemU.Text & "' "
' For Debugging
' MsgBox(strSQL)
cmd.Connection = conn
cmd.CommandText = strSQL
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error")
Finally
conn.Close()
End Try
Edit 1 :
A " sign was double in the line "WHERE [Item] ..."
Edit 2 :
Changed Convert(DOUBLE, Quantity) to Convert(DOUBLE, [Quantity])
Edit 3 : Remark for debugging.
' For Debugging
' MsgBox(strSQL)
Edit 4 : Added the missing ) to Convert(DOUBLE, '" & CDbl(AddU.Text) & "', " right at the end.
Edit 5 : changed )' to ')
Edit 6 : Now with CDec() instead of Convert(Double, )
Edit 7 : CDbl(AddU.Text.Replace(",", "."))
Edit 8 : Removed the ' around the CDbl(AddU.Text)
Edit 9 : replaced the CDec with CDbl
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