什么是将MySQL数据库与VB.NET连接的ConnectionString

时间:2018-11-15 06:58:15

标签: mysql vb.net

我正在使用以下代码将我的App表单VB.NetMySQL表数据库连接:

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

    Dim str As String = "data source=localhost;Initial Catalog=tabledb;user id=root;password=password1234"
    Dim con As New SqlConnection(str)
    con.Open()

    Dim com As String = "Select * from springdata where rfid_tag='" & Rfid_tagTextBox.Text & "'"
    Dim cm As New SqlCommand(com, con)
    Dim rd As SqlDataReader = cm.ExecuteReader()

    If rd.Read() = True Then
        MessageBox.Show("Valid username and password")
    Else
        MessageBox.Show("Invalid username and password", caption:="login")
    End If
End Sub

但是当我运行该应用程序时,出现了这个错误:

  

其他信息:与网络有关或与实例有关的错误   建立与SQL Server的连接时发生。服务器   找不到或无法访问。验证实例名称   是正确的,并且该SQL Server配置为允许远程   连接。 (提供者:命名管道提供者,错误:40-无法   打开与SQL Server的连接)

ConnectionString一起使用的正确MySQL 5.7是什么。

1 个答案:

答案 0 :(得分:1)

下面的连接字符串是SQL Server connection string

Dim str As String = "data source=localhost;Initial Catalog=tabledb;user id=root;password=password1234"

根据MySQL Connector .NET connection string,您应提供服务器名称,端口号(如果使用其他端口),数据库名称和凭据,如下所示:

Dim str As String = "Server=localhost;Port=3306;Database=tabledb;Uid=root;Pwd=password1234"

此外,您应该使用带有参数的MySqlConnectionMySqlCommandMySqlDataReader实例,而不是在查询字符串中使用值串联(确保首先添加对MySql.Data.dll的引用):

Using con As New MySqlConnection(str)
    con.Open()

    Dim com As String = "Select * from springdata where rfid_tag=@tag"

    Using cm As New MySqlCommand(com, con)
        cm.Parameters.Add("@tag", MySqlDbType.VarChar).Value = Rfid_tagTextBox.Text

        Dim rd As MySqlDataReader = cm.ExecuteReader()

        ' Check if any rows exist
        If rd.HasRows = True Then
            ' do something
        Else
            ' do something else
        End If
    End Using
End Using
相关问题