How to update data in table datagridview in vb.net - vb.net

i used this coding for my update button to update data in my table in datagridview but it is still shows error. i need some help to solve this problem
Dim MyItems As Integer
Dim MyItemNo As Integer
Dim ItemDescription As String
MyItems = GridViewItems.CurrentRow.Index
MyItemNo = GridViewItems.Item(0, MyItems).Value
ItemDescription = GridViewItems.Item(1, MyItems).Value
Dim SqlQuery As String = " UPDATE ITEMS = '" & MyItems & "'WHERE Item_No = " & MyItemNo & ""
Dim SqlCommand As OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = conn
.ExecuteNonQuery()
End With

Your use of the UPDATE sql statement is wrong. The correct syntax is
UPDATE <tablename> SET <field1> = <value>, <field2> = <value> WHERE <field3> = <value>
but there is also the problem of string concatenation that should be addressed.
So you could rewrite your code as
Dim SqlQuery As String = "UPDATE yourTableName SET ITEMS = ? WHERE Item_No = ?"
Dim SqlCommand As OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = conn
.Parameters.AddWithValue("#p1", MyItems)
.Parameters.AddWithValue("#p2", MyItemNo)
.ExecuteNonQuery()
End With
This is an example of a parameterized query. You should always use this approach when you need to pass values submitted by your user to your database. Without this your code is open to SQL Injection and other parsing problems

Related

Update Query Doesn't Work But No Error

(I code VB.NET and use ms access 2016 as database)
I execute this query but nothing happen. I wonder whats wrong. no error when i run it. i debugged it and all the values in the variables are also correct.
no changes happened in my db too
If Not (TextBoxID.Text = "" Or TextBoxNama.Text = "") Then
Try
Dim sqlquery As String = "UPDATE tblEmployees SET Nama = #nama WHERE IDEmployee = #ide"
Dim sqlcommand As New OleDbCommand
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#ide", TextBoxID.Text)
.Parameters.AddWithValue("#nama", TextBoxNama.Text)
.Connection = FormMain.conn
.ExecuteNonQuery()
End With
ButtonEdit.Text = "EDIT"
ButtonEdit.Image = My.Resources.edit
GroupBox1.Enabled = False
ButtonNew.Enabled = True
Catch ex As Exception
MsgBox(ex.Message)
End Try
Else
MsgBox("Data cannot be empty!")
End If
The problem is that MS Access doesn't have named parameters - but rather positional parameters.
So you must specify the parameters in the correct order in which they appear in your SQL statement. And you're not doing to right now.
Change your code to this:
If Not (TextBoxID.Text = "" Or TextBoxNama.Text = "") Then
Try
Dim sqlquery As String = "UPDATE tblEmployees SET Nama = #nama WHERE IDEmployee = #ide"
Dim sqlcommand As New OleDbCommand
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#nama", TextBoxNama.Text)
.Parameters.AddWithValue("#ide", TextBoxID.Text)
.Connection = FormMain.conn
.ExecuteNonQuery()
You must set the value for #nama first, before you set the value for #ide, since that's the order in which these parameters appear in your MS Access SQL statement.

Delete all data in MS Access database

Here is the code I am using :
Try
Dim SqlQuery As String = "DELETE FROM tblEXcel WHERE ID = " & id & ";"
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = conn
.ExecuteNonQuery()
End With
MsgBox("One record deleted..")
Catch ex As Exception
MsgBox(ex.Message, vbOKOnly, "Clear Measurement Table!")
End Try
For DataBindings you can use this...
Do While ExampleBindingSource.Count > 0
ExampleBindingSource.RemoveCurrent()
Loop
Remove WHERE ID = " & id. Then ALL the rows will be deleted.
So, simply change your SQL command to:
Dim SqlQuery As String = "DELETE FROM tblEXcel"
use below statement:
delete * from tblName
Dim SqlQuery As String = "DELETE * FROM tblEXcel WHERE ID = " & id & ";"
Dim MySQLCON As MySqlConnection = New MySqlConnection("Data Source=localhost;Database=test;User ID=root;Password=mysql;")
Dim COMMAND As MySqlCommand
MySQLCON.Open() /Open your Connection
Dim DELETERECORD As String = "DELETE * FROM tblEXcel WHERE ID= #id"
COMMAND = New MySqlCommand(DELETERECORD, MySQLCON)
COMMAND.Parameters.AddWithValue("#id", userID.Text) /userID.Text is the string of the users ID
COMMAND.ExecuteNonQuery()
MySQLCON.Close() /Always Close your Connection
MySQLCON.Dispose() /Always Dispose of your Connection
Note:
The way you where doing it was vulnerable to MySQL Injection Attacks. If you have a lot of MySQL Code in your application, i advise you to rewrite it in the way so it is not vulnerable.

How to concat to access cell using vb.net

I want to concat(add to what already exist) to an access cell using the text from a vb.net textbox. I tried using UPDATE but I'm getting a syntax error. This is what I tried so far
Dim ds As New DataSet()
Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\equip_full.mdb;Jet OLEDB:Database Password=matt"
Dim db As String = "Update INTO Equipment set TypeItem = ISNULL(TypeItem, '') & #EquipmentItem WHERE EquipmentCat = #category"
Using cn As New OleDbConnection(ConnectionString)
Using cmd = New OleDbCommand(db, cn)
cn.Open()
cmd.Parameters.Add("#EquipmentItem", OleDbType.VarWChar).Value = Form4.TextBox1.Text & ";"
cmd.Parameters.Add("#category", OleDbType.VarWChar).Value = Me.item_text.Text
Using reader = cmd.ExecuteReader()
'some code...
End Using
End Using
End Using
The correct syntax for an Update query is
UPDATE tablename SET field=value, field1=value1,.... WHERE condition
Then you need to remove that INTO that is used in the INSERT queries
Dim db As String = "Update Equipment set TypeItem = .... " &
"WHERE EquipmentCat = #category"
After fixing this first syntax error, then you have another problem with ISNull
ISNull is a boolean expression that return true or false.
If you want to replace the null value with an empty string you need the help of the IIF function that you could use to test the return value of ISNull and prepare the base string to which you concatenate the #Equipment parameter.
Something like this
Dim db As String = "Update Equipment " & _
"set TypeItem = IIF(ISNULL(TypeItem),'', TypeItem) & #EquipmentItem " & _
"WHERE EquipmentCat = #category"

I can not read from database Visual basic

Dim conStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\databaseVB\bakery.accdb"
Dim conn As New OleDbConnection(conStr)
Dim cmd As New OleDbCommand
Dim reader As OleDbDataReader
Dim Item(5) As String
Dim key = TextBox1.Text
conn.Open()
cmd.Connection = conn
1>>>>> 'cmd.CommandText = "SELECT * FROM Member WHERE number = 3"
2>>>>> cmd.CommandText = "SELECT * FROM Member WHERE number = '" & key & "'"
MessageBox.Show(cmd.CommandText)
reader = cmd.ExecuteReader()
While reader.Read
Item(0) = reader("Number").ToString
Item(1) = reader("FirstName").ToString
Item(2) = reader("LastName").ToString
Item(3) = reader("User").ToString
Item(4) = reader("Pass").ToString
End While
MessageBox.Show(Item(1).ToString)
conn.Close()
from 1>>> I can read Item in databaes
from 2>>> I can not read Item
Try using a parameterized query string:
cmd.CommandText = "SELECT * FROM Member WHERE number = #Number"
After this add your parameters.
//cmd.Parameters.Add("#Number", SqlDbType.Int).Value = 3;
//It is better to use .TryParse(), incase your users write non numerical values in the Textbox
cmd.Parameters.Add("#Number", SqlDbType.Int).Value = (int)TextBox1.Text;
Additionally you need to watch your data types. 3 is of type int, but TextBox1.Text is of type string. You need to parse the string to int in order for it to work.
This should do the trick and prevent ugly syntax juggling, while mixing strings and variables; And prevent you from SQL Injection attacks.

Deleting-Updating a dataview

I need your help PLEASE!
I have a table: tblCustomer. (serial,Name,Email,Address)
I did the following:
insert-update-delete in dataset(that contains the table tblCustomer)
What I need to do, and I need your help in it, is:
insert-update-delete in dataview.
I tried to do the following:
Dim dv As New DataView(_DataSet.Tables(0))
' select deleted rows
dv.RowStateFilter = DataViewRowState.Deleted
For _irow As Long = 0 To dv.Table.Rows.Count - 1
' if serial is null, that means the row is new and deleted
' so no need to add it to database
If Not IsDBNull(dv!serial) Then
' delete row from database
Dim _SQL As String = "DELETE FROM tblCustomer WHERE Serial = " & dv!serial.ToString
' open the connection and execute the delete command
Dim strconnection As String = "Data Source=EASMAR-PC;Initial Catalog=Database Connection;Integrated Security=True;"
Dim _cn As SqlConnection = New SqlConnection(strconnection)
_cn.Open()
Dim cmd As New SqlCommand
cmd.CommandText = "Delete from tblCustomer where serial= '" & txtSerial.Text & "'"
End If
Next
I am getting this error: Conversion from string "serial" to type 'Integer' is not valid.
On this line: If Not IsDBNull(dv!serial) Then
And the same error on: Dim _SQL As String = "DELETE FROM tblCustomer WHERE Serial = " & dv!serial.ToString
Can you help me PLEASE.
Thank you.
what type is serial? Integer I guess, from the error. Plus it seems you're passing the literal string value "serial" instead of a number.
Also, in your two DELETE statements you're passing it both WITH and WITHOUT ' '.
remove those ' '.
And what's that _SQL string variable? you're not using it.
Try:
If Not IsDBNull(dv!serial) Then
' open the connection and execute the delete command
Dim strconnection As String = "Data Source=EASMAR-PC;Initial Catalog=Database Connection;Integrated Security=True;"
Dim _cn As SqlConnection = New SqlConnection(strconnection)
_cn.Open()
Dim cmd As New SqlCommand
cmd.CommandText = "Delete from tblCustomer where serial= " & txtSerial.Text
End If