Rabeea Qabaha
Rabeea Qabaha

Reputation: 378

check if the phone number exist in ms table

how i can know if the phone number exist in ms database or not ?

I'm using this code but i have error , i think i need to get all phone number as array and search in array if the number exist or not .

Dim number As String
    con.Open()
    Dim sql As String = "select cphone from cust "
    Dim cmd As New OleDbCommand(sql, con)
    Dim dr As OleDbDataReader
    dr = cmd.ExecuteReader
    While dr.Read
        number = dr(5)
    End While
    con.Close()

    If TextBox5.Text = number Then
        MsgBox("exist")
    Else
        MsgBox("NOT-exist")
    End If

but i think there is easy way to do this , any help please

enter image description here enter image description here

Upvotes: 0

Views: 125

Answers (2)

Zohar Peled
Zohar Peled

Reputation: 82514

Try this:

Dim ReturnValue as object
Dim sql As String = "select 1 from cust where cphone = @cphone"
using (Con as OleDbConnection = New OleDbConnection(ConnectionString)) 
    using (cmd As OleDbCommand = New OleDbCommand(sql, Con))
        cmd.Parameters.Add(@cphone).Value = TextBox5.Text
        Con.Open()
        ReturnValue = cmd.ExecureScalar()
        Con.Close()
        If ReturnValue Is Nothing Then
            MsgBox("exist")
        Else
            MsgBox("NOT-exist")
        End If
    end using
end using

Explanations:

  • Using blocks provides a convenient syntax that ensures the correct use of IDisposable objects.
  • Parametized queries ensure sql injection safety
  • Using ExecuteScalar returns the first value that returns from a query. in this case, if the text in TextBox5 doesn't match any cphone in the database, Nothing will return, this is why I've used the ReturnValue object

Note: Code written directly here, I might have made some syntax mistakes, but this is the general direction you should take your code to.

Upvotes: 1

Rohit Vipin Mathews
Rohit Vipin Mathews

Reputation: 11787

You can do checking in Query

Dim sql As String = "select cphone from cust where cphone = " + TextBox5.Text

Instead of the number you can even return a BIT or TOP 1 You can use ExecuteScalar which would improve performance as well.

Upvotes: 0

Related Questions