Do you often have to get a datafield from the DB? Quickly done!-VBForums
Results 1 to 3 of 3

Thread: Do you often have to get a datafield from the DB? Quickly done!

  1. #1

    Thread Starter
    New Member
    Join Date
    Apr 2016
    Posts
    12

    Cool Do you often have to get a datafield from the DB? Quickly done!

    Function used to get a single item of information from a table, given a valid query

    Example...

    Code:
    Dim Last_Name as String = GetSingleField("SELECT LastName FROM Clients WHERE ID = '" & Client.ID & "'")
    Code:
    Public Function GetSingleField(SqlStr As String, ConnString as String) As String
    
    	Dim sAnswer As String = ""
    	Dim myCommand As SqlCommand
    	Dim myreader As SqlDataReader
    
    	Using myConnection As New SqlConnection(ConnString)
    	
    		myConnection.Open()
    		myCommand = New SqlCommand(SqlStr.ToString, myConnection)
    		myreader = myCommand.ExecuteReader
    
    		If myreader.HasRows Then
    			myreader.Read()
    			Return myreader(0).ToString
    		Else
    			Return ""
    		End If
    		myreader.Close()
    		myCommand.Dispose()
    		
    	End Using
    
    	Return sAnswer
    
    End Function

  2. #2
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    9,201

    Re: Do you often have to get a datafield from the DB? Quickly done!

    You should always parameterize your queries, if for nothing else to at least protect against SQL injections.

  3. #3

    Thread Starter
    New Member
    Join Date
    Apr 2016
    Posts
    12

    Re: Do you often have to get a datafield from the DB? Quickly done!

    If the SQL isn't managed directly form the program, then absolutely yes.
    But If I'm SURE that the SQL comes only from my code, then I tend to be lenient... :-)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width

Survey posted by VBForums.