VB.Net无法连接到SQL

时间:2015-11-07 17:57:09

标签: sql vb.net

Private Sub Button5_Click_1(sender As Object, e As EventArgs) Handles Button5.Click
    Dim connetionString As String
    Dim cnn As SqlConnection
    connetionString = "Server=localhost;Initial Catalog=acernis;User ID=root;Password=password"
    cnn = New SqlConnection(connetionString)
    Try
        cnn.Open()
        MsgBox("Connection Open ! ")
        cnn.Close()
    Catch ex As Exception
        MsgBox("Can not open connection ! ")
    End Try
End Sub

目前在我的代码中我有SQL用户名以上的代码,并且传递是正确的,因为数据库。我正在运行WAMP并且正在使用Navicat以确保我可以连接。有什么问题?

2 个答案:

答案 0 :(得分:0)

如果您使用的是MS SQL服务器,则问题在于连接字符串。试试这个:

connetionString = "Server=localhost;Database=acernis;User ID=root;Password=password"

但是,如果您的意思是MySQL,那么您需要更改的不仅仅是连接字符串

试试这个:

Private Sub Button5_Click_1(sender As Object, e As EventArgs) Handles Button5.Click
    Dim connetionString As String
    connetionString = "Server=localhost;Database=acernis;Uid=root;Pwd=password;"

    Dim conn As New MySqlConnection(connetionString)
    Try
        conn.Open()
        MsgBox("Connection Open ! ")
    Catch ex As MySqlException
        MsgBox("Can not open connection Error: " & ex.ToString())
    Finally
        conn.Close()
    End Try
End Sub

找出最适合您引用网站的连接字符串

http://www.connectionstrings.com/

答案 1 :(得分:0)

Private Sub Button5_Click_1(sender As Object, e As EventArgs) Handles Button5.Click
Dim connetionString As String
Dim cnn As SqlConnection
connetionString = "Server=localhost\<InstanceName>;Initial Catalog=acernis;User ID=root;Password=password"
cnn = New SqlConnection(connetionString)
Try
    if not cnn.State=ConnectionState.Open then cnn.Open()
    MsgBox("Connection Open ! ")
    cnn.Close()
Catch ex As Exception
    MsgBox("Can not open connection ! ")
End Try

End Sub

根据观察,如果您使用的是SQL Server,则需要在<Instance Name>属性中指定Server

另外,不要在catch部分使用类Exception,而是使用特定的exceptoin类;在这种情况下,请使用SQLException