I want a specific value of an SQL Database column to appear in a textbox, but there is an error with my code which appears to be at this line:
Dim lrd As MySqlDataReader = cmd.ExecuteReader()
Imports MySql.Data.MySqlClient
Public Class Main
Dim conn As MySqlConnection
Private Sub Main_Load(sender As Object, e As EventArgs) Handles Me.Load
conn = New MySqlConnection()
conn.ConnectionString = "server='127.0.0.1';user id='root';Password='test';database='snipper'"
Try
conn.Open()
Catch myerror As MySqlException
MsgBox("Error Connecting to Database. Please Try again !")
End Try
Dim strSQL As String = "SELECT * FROM snippets"
Dim da As New MySqlDataAdapter(strSQL, conn)
Dim ds As New DataSet
da.Fill(ds, "snippets")
With ComboBox1
.DataSource = ds.Tables("snippets")
.DisplayMember = "title"
.SelectedIndex = 0
End With
Dim cmd = New MySqlCommand("SELECT snippet FROM snippets where title=" & cbSnippets.Text)
cmd.Connection = conn
Dim lrd As MySqlDataReader = cmd.ExecuteReader()
While lrd.Read()
txtCode.Text = lrd("snippet").ToString()
End While
End Sub
What may be wrong?
PLEASE USE PARAMETERISED QUERIES
Your actual problem originates from this line:
Dim cmd = New MySqlCommand("SELECT snippet FROM snippets where title=" & cbSnippets.Text)
Supposing I enter "This is a test"
into the text box, the SQL becomes
SELECT snippet
FROM snippets
WHERE title=This is a test
With no quotes around the text, it should be:
SELECT snippet
FROM snippets
WHERE title='This is a test'
However, if I were to write "''; DROP TABLE Snippets; -- "
In your text box you may find yourself without a snippets table!.
You should always use parameterised queries, this is safer and more efficient (it means query plans can be cached and reused so don't need to be compiled each time);
Dim cmd = New MySqlCommand("SELECT snippet FROM snippets where title = @Title")
cmd.Parameters.AddWithValue("@Title", cbSnippets.Text)
Dim lrd As MySqlDataReader = cmd.ExecuteReader()
Try changing this line :
Dim cmd = New MySqlCommand("SELECT snippet FROM snippets where title=" & cbSnippets.Text)
to :
Dim cmd = New MySqlCommand("SELECT snippet FROM snippets where title='" & cbSnippets.Text & "'")
Note the quotes around the string you'l be searching for. You could aswell use the like
comparison too :
Dim cmd = New MySqlCommand("SELECT snippet FROM snippets where title like '%" & cbSnippets.Text & "%'")
The %
symbol acts as a wildcard. In this case, that would look for any string containing the searched text instead of string being exactly the same as the searched text.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.