2013-12-23 59 views
0

我想要一個SQL數據庫列的特定值出現在一個文本框,但我的代碼這似乎是在這一行錯誤:顯示SQL的列項

暗淡LRD作爲了MySqlDataReader = cmd.ExecuteReader()

Imports MySql.Data.MySqlClient 

公共類主要

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 

什麼可能是錯誤的?

+1

你得到了什麼錯誤,它發生在哪裏? – BWS

回答

2

嘗試修改此行:

Dim cmd = New MySqlCommand("SELECT snippet FROM snippets where title=" & cbSnippets.Text) 

到:

Dim cmd = New MySqlCommand("SELECT snippet FROM snippets where title='" & cbSnippets.Text & "'") 

注意字符串you'l來搜索周圍的報價。你可以藏漢使用like比較過:

Dim cmd = New MySqlCommand("SELECT snippet FROM snippets where title like '%" & cbSnippets.Text & "%'") 

%符號作爲通配符。在這種情況下,它會查找包含搜索文本的任何字符串,而不是與搜索文本完全相同的字符串。從該行

+0

謝謝了!成功了! – suchanoob

+0

不客氣。但事實上,雖然這將起作用,但使用GarethD建議的參數化查詢是最佳做法。 –

+0

我肯定會使用參數化查詢。謝謝你們倆! – suchanoob

3

PLEASE USE PARAMETERISED QUERIES

您的實際問題來源:

Dim cmd = New MySqlCommand("SELECT snippet FROM snippets where title=" & cbSnippets.Text) 

假如我進入"This is a test"到文本框,SQL成爲

SELECT snippet 
FROM snippets 
WHERE title=This is a test 

與各地暫無報價文本,它應該是:

SELECT snippet 
FROM snippets 
WHERE title='This is a test' 

但是,如果我要寫"''; DROP TABLE Snippets; -- "在您的文本框中,您可能會發現自己沒有片段表!

你應該總是使用參數化查詢,這是更安全和更有效率(這意味着查詢計劃可以緩存和重用,所以不需要每次編譯);

Dim cmd = New MySqlCommand("SELECT snippet FROM snippets where title = @Title") 
cmd.Parameters.AddWithValue("@Title", cbSnippets.Text) 
Dim lrd As MySqlDataReader = cmd.ExecuteReader() 
+0

非常感謝您的建議!成功了! – suchanoob