sql SELECT query using vb.net

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ravenfrost
    New Member
    • Apr 2007
    • 9

    #1

    sql SELECT query using vb.net

    Hello,

    I'm trying to query a sql table to see if a value already exists.

    Code:
    strMAC = "11:22:33:44:55:66"
    Call MsgBox(QueryDB("SELECT * FROM main WHERE MAC = '" & strMAC & "'", conn))
    
    Function QueryDB(ByVal sql As String, ByVal conn As SqlConnection)
      QueryDB = 0
      Dim cmd As SqlCommand = Nothing
      Dim dr As SqlDataReader = Nothing
      cmd = New SqlCommand(sql, conn)
      dr = cmd.ExecuteReader(CommandBehavior.SingleResult)
      dr.Read() ' Read one row from the table
      QueryDB = dr(0)
    End Function
    I can get that to return the field correctly. But, if the row doesn't exists, it errors out. Is there any way to check for that null rows? Also, is this a good way to be checking for values? Thanks.
    Last edited by Killer42; Apr 17 '07, 03:13 AM. Reason: Added [CODE] tag
  • iburyak
    Recognized Expert Top Contributor
    • Nov 2006
    • 1016

    #2
    Try something like this:

    Code:
    If (dr.Read())
    {
         QueryDB = dr(0);
    }
    Good Luck.

    Comment

    • smith andersen

      #3
      this is a lot of code, but it works everytime.
      the function checks if the email address entered is in the database. hope this helps

      Code:
      Function chkForDuplicates(ByVal user As String, ByVal code As String) As Integer
      
              Dim queryString As String = "SELECT COUNT ([Email]) FROM [Users] WHERE ([Email] = @Username)"
              Dim dbCommand As System.Data.IDbCommand = New System.Data.OleDb.OleDbCommand
              dbCommand.CommandText = queryString
              dbCommand.Connection = dbConnection
      
              Dim dbParam_username As System.Data.IDataParameter = New System.Data.OleDb.OleDbParameter
              dbParam_username.ParameterName = "@Username"
              dbParam_username.Value = user
              dbParam_username.DbType = System.Data.DbType.String
              dbCommand.Parameters.Add(dbParam_username)
      
              Dim result As Integer = 0
              dbConnection.Open()
      
              Try
                  result = dbCommand.ExecuteScalar
              Finally
                  dbConnection.Close()
              End Try
      
              If result > 0 Then
                  Return True
              Else
                  Return False
              End If
          End Function

      Comment

      Working...