连接必须有效并在vb 2008中打开

时间:2015-09-20 02:18:09

标签: mysql vb.net

Imports MySql.Data.MySqlClient
Public Class daftar

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim Cn As New MySqlConnection
    Dim str As String
    Dim dt As New DataTable
    Dim cmd As New MySqlCommand
    Cn = New MySqlConnection("server=localhost;" _
       & "user id=root;" _
       & "password=;" _
       & "database=loginapp")
    Try
        Cn.Open()
        MsgBox("Connected")
    Catch ex As Exception
        MsgBox("Failed Connection " & vbCrLf & "Error Message : " & ex.Message, MsgBoxStyle.Critical, "Peringatan")
    End Try
    cmd.Parameters.AddWithValue("@id", user.Text)
    cmd.Parameters.AddWithValue("@pass", pass.Text)
    str = "INSERT INTO tbluser(Username,Password) VALUES (@id,@pass)"
    cmd = New MySqlCommand(str)
    cmd.ExecuteNonQuery()
    MessageBox.Show("Insert Data Siswa Berhasil Dilakukan")
    Cn.Close()
End Sub
End Class

我遇到“cmd.ExecuteNonQuery”问题,它有一条消息“连接必须有效并且打开”任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

我不相信您了解New关键字的作用。您正在创建新命令并向其添加参数,然后通过重新创建MySqlCommand的全新实例来销毁您的工作。除了这个错误,你永远不会设置命令来使用你打开的连接。您最好再次阅读文档。