连接MySQL vb.net

时间:2018-02-13 10:52:04

标签: vb.net

我使用的是Visual Studio 2017.我不知道它如何与MySQL配合使用。我的问题是我无法连接到我的SQL数据库。我不知道我是否正确地设置了代码,因为我已经研究过,有很多意见如何放置代码,但Visual Studio 2017没有代码。

Imports System.Data.SqlClient

公共类FormDatabaseMySQL

Dim connection As New SqlConnection("datasource=localhost;port=3306;username=root;password=;database=bukuakaunrumah")
Dim command As New SqlCommand

Private Sub FormDatabaseMySQL_Load(sender As Object, e As EventArgs) Handles MyBase.Load



End Sub

Private Sub ButtonBack_Click(sender As Object, e As EventArgs) Handles ButtonBack.Click
    Me.Hide()
    FormFront.Show()

End Sub

Private Sub ButtonSubmit_Click(sender As Object, e As EventArgs) Handles ButtonSubmit.Click
    Dim command As New SqlCommand("INSERT INTO `accountinfo`(`AccountID`, `AccountName`, `AccountPassword`) VALUES (@accountID,@accountName,@accountPassword)", connection)

    command.Parameters.Add("@AccountID", SqlDbType.VarChar).Value = TextBoxID.Text
    command.Parameters.Add("@AccountName", SqlDbType.VarChar).Value = TextBoxName.Text
    command.Parameters.Add("@AccountPassword", SqlDbType.VarChar).Value = TextBoxPassword.Text

    connection.Open()

    If command.ExecuteNonQuery() = 1 Then

        MessageBox.Show("Successful Registered", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)

    Else
        MessageBox.Show("Error")


    End If
    connection.Close()


End Sub 
End Class

这是我的输出。 Figure 1

修改 它显示错误:Figure 2

编辑2: 即使我已经下载了MySQL Connector Figure 3

,我仍然有错误

2 个答案:

答案 0 :(得分:1)

System.Data.SqlClient命名空间是SQL Server的.NET Framework数据提供程序。 如果您尝试连接MySQL DB,最好使用它:

Imports MySql.Data
Imports MySql.Data.MySqlClient

并像这样连接:

Dim conn As New MySql.Data.MySqlClient.MySqlConnection
Dim myConnectionString as String

myConnectionString = "server=localhost;" _
            & "uid=root;" _
            & "pwd=;" _
            & "database=bukuakaunrumah"

Try
  conn.ConnectionString = myConnectionString
  conn.Open()

Catch ex As MySql.Data.MySqlClient.MySqlException
  MessageBox.Show(ex.Message)
End Try

PS:尝试替换"数据源"与"服务器"在你的连接配置

答案 1 :(得分:1)

首先,您需要安装MySQL NET Connector。

你可以找到它here

您可以找到它的文档here和参考列表here

如果您想查看代码示例,请查看this