Skip to content
Advertisement

vb.net select statement failing

I have this code to populate a DataGridView (DGV) the goal is to only populate the DGV with data from the LinkTable where one of its fields ytSiteType is equal to a global variable set on another form. The variable is gvSLT and I have tested that gvSLT makes the trip to the new form with the correct value.
I have solved the problem by adding an If statement to the SQLiteDataReader routine.
I will post the code below with these two line of code that fail.

 cmd.CommandText = "SELECT * FROM LinkTable WHERE ytSiteType =" & gvSLT
 cmd.CommandText = "SELECT * FROM LinkTable WHERE ytSiteType = 'gvSLT'"

Here is the the code that is working

        Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
        conn.Open()

        Using cmd As New SQLiteCommand("", conn)

            cmd.CommandText = "SELECT * FROM LinkTable"
            'cmd.CommandText = "SELECT * FROM LinkTable WHERE ytSiteType =" & gvSLT
            'cmd.CommandText = "SELECT * FROM LinkTable WHERE ytSiteType = 'gvSLT'"
            'cmd.CommandText = "SELECT * FROM LinkTable WHERE ytSiteType = 'News'"

            Using rdr As SQLite.SQLiteDataReader = cmd.ExecuteReader
                'dgvLinks.DataSource = rdr
                'Statement Above use when DB is bound to dgvLinks
                '=================================================

                While rdr.Read()
                    intID = CInt((rdr("LID")))
                    strChannelName = rdr("ytChannelName").ToString
                    strLinkAddress = rdr("ytLinkAddress").ToString
                    strLinkType = rdr("ytSiteType").ToString
                    If strLinkType = gvSLT Then
                        dgvLinks.Rows.Add(intID, strChannelName, strLinkAddress)
                        rowCount = rowCount + 1
                    End If
                End While

            End Using

The question is “Why are the commented out SELECT statements failing”

Advertisement

Answer

Your first example fails because, if ytSiteType is a field of string type, you are concatenating the value of gvSLT without putting it inside single quotes.

The second example fails because you are putting inside single quotes the literal text “gvSLT” not the value of gvSLT.

The third example, I am not sure, but probably fails because there is no record with exactly the “News” value.

You should always use parameters to avoid these problems and others like SqlInjection, parsing decimal separator in numeric values and problems if the input gvSLT contains itself one or more single quotes.

So a simple solution should be:

cmd.CommandText = "SELECT * FROM LinkTable WHERE ytSiteType = @site"
cmd.Parameters.Add("@site", DbType.String).Value = gvSLT
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement