How do you check if record is available in the database

korae

Member
Joined
Jan 24, 2010
Messages
22
Programming Experience
Beginner
I have this code that Deletes a record by its IP address inputted by the user. How do you check if that record is available? how do evaluate first that the IP address inputted is not in the database before deleting anything? in vb 6.0 I used to do this line:

If rs.EOF And rs.BOF Then

but it doesn't work anymore in vb 2008

VB.NET:
If TextBox1.Text = "" Then
                    MsgBox("Input IP Address", MsgBoxStyle.OkOnly, Title:="")
                Else
                    Dim myConnection As OleDbConnection = New OleDbConnection
                    Dim myCommand As OleDbCommand = New OleDbCommand
                    myConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Network_Info.mdb"

                    myConnection.Open()

                    myCommand.Connection = myConnection
                    myCommand.CommandText = "DELETE * from Computer_Connection_Info WHERE IP_Address ='" & TextBox1.Text & "'"

                    myCommand.ExecuteNonQuery()
End If
 
Check if an item already exist in the database

This is how I code it in VB .Net 2008

Imports System.Data
Imports System.Data.SqlClient

Dim myconn As New SqlConnection(Data.ConnString)
Dim mycmd As New SqlCommand
Dim strqry As String
strqry = "(SELECT * FROM tbSample where [IpAdd]='" & txtIpAdd.Text & "')"

myconn.Open()
mycmd = New SqlCommand(strqry, myconn)
Dim dr As SqlDataReader = mycmd.ExecuteReader
If dr.HasRows Then 'found existing data
MessageBox.Show ("IP already exist!")
Else 'nothing found
MessageBox.Show ("IP not exist!")
End If
 
If all you are doing is deleting the record if it exists, I wouldnt even bother with checking. No need to run two queries, one to check for the record and the second to delete. Just run the delete, a record action count can be returned at the end to tell you if it deleted any records or not with just the one hit to the database.
 
All you need to change in the original code is this:
VB.NET:
Dim recordsDeleted As Integer = myCommand.ExecuteNonQuery()
You can then test the value of recordsDeleted. If it's zero then there were no matching records.
 
Back
Top