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
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.
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... :-)