如何使用查询写入VB.net中的Mysql数据库

时间:2018-02-12 13:04:32

标签: mysql sql vb.net forms basic

我正在尝试创建一个从Mysql数据库写入和读取的小程序。阅读部分进展顺利,但我在写部分有点困难。

这是我的代码:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Absenden.Click
    Dim conn As New MySqlConnection
    Dim command As MySqlCommand
    Dim myConnectionString As String
    myConnectionString = "server=Nothing;uid=to;pwd=see;database=here;"
    conn.ConnectionString = myConnectionString

    Try
        conn.Open()
        Dim Querywrite As String
        Querywrite = "select * FROM here.message INSERT INTO message admin='" & TB_Name.Text & "' and message='" & TB_Nachricht.Text & "' and Server='" & TB_Server.Text & "' and status='" & TB_Status.Text & "' "
        command = New MySqlCommand(Querywrite, connection)
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
    conn.Close()
End Sub

Querywrite部分是我认为的问题。输入来自Windows窗体中的文本框。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

也许,如果有人给你看过一次,那么你就会明白这一点。主要是始终使用参数;您不仅可以避免轻微的sytax和类型错误,还可以避免重大的恶意输入灾难。我猜到你的字段的数据类型。请检查您的数据库中的类型并相应地调整您的代码。

Private Sub InsertData()
        Dim strQuery As String = "Insert Into message (admin, message, Server, status) Values (@admin, @message, @Server, @status);"     
        Using cn As New MySqlConnection("your connection string")
            Using cmd As New MySqlCommand With {
                    .Connection = cn,
                    .CommandType = CommandType.Text,
                    .CommandText = strQuery}
                cmd.Parameters.Add("@admin", MySqlDbType.VarString).Value = TB_Name.Text
                cmd.Parameters.Add("@message", MySqlDbType.VarString).Value = TB_Nachricht.Text
                cmd.Parameters.Add("@Server", MySqlDbType.VarString).Value = TB_Server.Text
                cmd.Parameters.Add("@status", MySqlDbType.VarString).Value = TB_Status.Text
                cn.Open()
                cmd.ExecuteNonQuery()
                cn.Close()
            End Using
        End Using
    End Sub