Search code examples
mysqlvb.netdatabase-connectionexecutereader

Reading value from database


I am trying to read a single entry from a database based on a parameter being passed into my function. I know the connection string is working as I use it elsewhere and my SQL statement works as I can execute it in SQL Server with no problem. The problem that I am having is with the "return" statement. No matter where I put it, where I declare it or where I put my While loop reading the database table I get the green squiggly on 'Return siteID' telling me "variable 'siteID' is used before it has been assigned a value"

Public Function GetSiteID(ByVal siteName As String) As String

    Dim strConnectionString2 As String = ConfigurationManager.ConnectionStrings("AVDataConnectionString").ConnectionString


    Dim strQueryString2 As String = "SELECT SourceSite.SourceSiteID FROM[AVData].[dbo].[SourceSite] JOIN [AVData].[dbo].[SourceSiteMetaTag] ON SourceSite.SourceSiteID=[SourceSiteMetaTag].[SourceSiteID] WHERE SourceSiteMetaTag.TagName='SiteType' AND SourceSiteMetaTag.TagValue='Network'order by [Description] asc AND SiteName = '" & siteName & "'"

    Dim connection2 As New SqlConnection(strConnectionString2)
    Dim command2 As New SqlCommand(strQueryString2, connection2)

    Dim siteID As String
    Try
        connection2.Open()
        Dim myReader As SqlDataReader = command2.ExecuteReader()
        While myReader.Read()
            siteID = myReader("SourceSiteID").ToString()
        End While
    Catch ex As Exception
        Throw ex
    Finally
        connection2.Close()
    End Try

    Return siteID

End Function

Solution

  • If myReader never reads (connection2 isn't able to open and the try/catch is tripped) then siteId would never be assigned a value.

    You can skirt around this issue by setting a value when you declare siteId

    Dim siteID As String = ""