Deleting-Updating a dataview - vb.net

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

Related

Visual basic - Incrementing the score

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim READER As MySqlDataReader
Dim Query As String
Dim connection As MySqlConnection
Dim COMMAND As MySqlCommand
Dim item As Object
Try
item = InputBox("What is the item?", "InputBox Test", "Type the item here.")
If item = "shoe" Then
Dim connStr As String = ""
Dim connection As New MySqlConnection(connStr)
connection.Open()
Query = "select * from table where username= '" & Login.txtusername.Text & " '"
COMMAND = New MySqlCommand(Query, connection)
READER = COMMAND.ExecuteReader
If (READER.Read() = True) Then
Query = "UPDATE table set noOfItems = noOfItems+1, week1 = 'found' where username= '" & Login.txtusername.Text & "'"
Dim noOfItems As Integer
Dim username As String
noOfItems = READER("noOfItems") + 1
username = READER("username")
MessageBox.Show(username & "- The number of items you now have is: " & noOfGeocaches)
End If
Else
MsgBox("Unlucky, Incorrect item. Please see hints. Your score still remains the same")
End If
Catch ex As Exception
MessageBox.Show("Error")
End Try
I finally got the message box to display! but now my code does not increment in the database, can anybody help me please :D
Thanks in advance
After fixing your typos (space after the login textbox and name of the field retrieved) you are still missing to execute the sql text that updates the database.
Your code could be simplified understanding that an UPDATE query has no effect if the WHERE condition doesn't find anything to update. Moreover keeping an MySqlDataReader open while you try to execute a MySqlCommand will trigger an error in MySql NET connector. (Not possible to use a connection in use by a datareader). We could try to execute both statements in a single call to ExecuteReader separating each command with a semicolon and, of course, using a parameter and not a string concatenation
' Prepare the string for both commands to execute
Query = "UPDATE table set noOfItems = noOfItems+1, " & _
"week1 = 'found' where username= #name; " & _
"SELECT noOfItems FROM table WHERE username = #name"
' You already know the username, don't you?
Dim username = Login.txtusername.Text
' Create the connection and the command inside a using block to
' facilitate closing and disposing of these objects.. exceptions included
Using connection = New MySqlConnection(connStr)
Using COMMAND = New MySqlCommand(Query, connection)
connection.Open()
' Set the parameter value required by both commands.
COMMAND.Parameters.Add("#name", MySqlDbType.VarChar).Value = username
' Again create the reader in a using block
Using READER = COMMAND.ExecuteReader
If READER.Read() Then
Dim noOfItems As Integer
noOfItems = READER("noOfItems")
MessageBox.Show(username & "- The number of items you now have is: " & noOfItems )
End If
End Using
End Using
End Using

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"

How to update data in table datagridview in 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

Sql in Visual Basic returning nothing while same query in Access returns right value

My code:
strConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=PIZZA.accdb"
strSql = "SELECT INGREDIENTNR AS NR FROM INGREDIENTS WHERE DESCRIPTION = '" & ingredients(counter * 2) & "'"
objConnection = New OleDbConnection(strConnectionString)
objCommand = New OleDbCommand(strSql, objConnection)
objConnection.Open()
objDataReader = objCommand.ExecuteReader(CommandBehavior.CloseConnection)
Dim strIngNr As String = objDataReader("NR")
Dim strIngNr As String = objDataReader("NR") gives the error: No data exists for the row/column.
But the same query in Access does return 14, which is the right value and what I want to get. What am I doing wrong?
Another thing: counter is the right value, tested that already.
And another thing: DESCRIPTION is a String