2017-10-11 159 views
-1

這是我的示例代碼mysql vb.net中更新查詢的正確語法是什麼?

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
     myConn = New MySqlConnection 
    myConn.ConnectionString = "server=localhost;userid=root;password=root;database=itss" 
    Dim reader As MySqlDataReader 

    Try 
     myConn.Open() 
     Dim query As String 
     query = "update itss.announcement set annoMessage = '" & TextBox1.Text & "' where idAnno = 3" 
     command = New MySqlCommand(query, myConn) 
     reader = command.ExecuteReader 
     myConn.Close() 
    Catch ex As Exception 
     MessageBox.Show(ex.Message) 
    Finally 
     myConn.Dispose() 
    End Try 
    'strMessage = TextBox1.Text 
    Form1.GroupBox1.Select() 
    Form1.Activate() 
    Form4.Activate() 
    Me.Hide() 
End Sub 

當我點擊出現異常的按鈕說

您的SQL語法錯誤;檢查對應於你的MySQL服務器版本使用附近的正確語法手冊的突破,挑戰昨天的舊格局,創造未來的N'位於第1行

+1

這是來自不使用參數。參數化你的SQL查詢,它會按你的預期工作。請閱讀更多信息:http://jmcilhinney.blogspot.com.au/2009/08/using-parameters-in-adonet.html – jmcilhinney

回答

1

的問題是,你使用reader = command.ExecuteReader上帶連接參數字符串的UPDATE語句。您應該使用ExecuteNonQuery與參數化查詢是這樣的:

myConn.Open() 
Dim query As String 
query = "update itss.announcement set annoMessage = @message where idAnno = 3" 
command = New MySqlCommand(query, myConn) 
command.Parameters.Add("@message", MySqlDbType.VarChar).Value = TextBox1.Text 
reader = command.ExecuteNonQuery() ' this is used for UPDATE statement 
myConn.Close() 

NB:用於從SELECT語句返回查詢結果ExecuteReader,即SELECT * FROM itss.announcement WHERE idAnno = 3

+0

出現錯誤。它表示'BC30311 \t'Integer'類型的值無法轉換爲'MySqlDataReader'。' –

+0

您不能通過使用ExecuteReader來將'UPDATE'查詢結果(這是一個'Integer'作爲總行受影響的值)分配給'MySqlDataReader'。按照建議使用'ExecuteNonQuery'並去除'ExecuteReader'。 –