使用 Visual Studio 中的 VB.NET 连接到本地 SQL 数据库的连接字符串问题

Connection string problem connecting to local SQL database using VB.NET in Visual Studio

我不明白为什么我无法连接我的 SQL Server Express LocalDB。我的连接字符串一直有问题。这是我试过的:

Imports System.Data.OleDb

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

        Dim conString As String        'Connection string
        Dim con As OleDbConnection     'Connecting to your database
        Dim Command As OleDbCommand    'Query  "What do you want in the database"

        'conString = "PROVIDER=System.Data.SqlClient v4.0; Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\DatabaseInnlogging.mdf;Integrated Security=True"
        'conString = "PROVIDER=SQLOLEDB; Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\DatabaseInnlogging.mdf;Integrated Security=True"
        'conString = "PROVIDER=System.Data.SqlClient; Data Source=C:\Users\Bruker\source\repos\InnloggingFørsøkv1\InnloggingFørsøkv1\DatabaseInnlogging.mdf;Integrated Security=True"
        'conString = "PROVIDER=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\Bruker\source\repos\InnloggingFørsøkv1\InnloggingFørsøkv1\DatabaseInnlogging.mdf;Integrated Security=True"
        'conString = "PROVIDER=System.Data.SqlClient v4.0; Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\DatabaseInnlogging.mdf;Integrated Security=True"

    Try
           con = New OleDbConnection(conString)
           con.Open()

            Command = New OleDbCommand("select * from LogInTable where UserID = ? and Password = ?", con)



            Dim parm1 As OleDbParameter, parm2 As OleDbParameter

            parm1 = Command.Parameters.Add("@UserID", OleDbType.VarChar)
            parm2 = Command.Parameters.Add("@Password", OleDbType.VarChar)
            parm1.Direction = ParameterDirection.Input
            parm2.Direction = ParameterDirection.Input

            parm1.Value = Me.TextBox1.Text
            parm2.Value = Me.TextBox2.Text

            Command.Connection.Open()
            Dim reader As OleDbDataReader

            If reader.Read = True Then
                Me.DialogResult = DialogResult.OK
            Else
                MsgBox("Invalid UserID or Password")
            End If

            reader = Command.ExecuteReader

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
End Sub

我尝试了几个连接字符串,但 none 正常。

但是对于数字 4,我得到了错误

Multiple-step OLE DB operation generated errors.check each OLE DB status value

其他导致错误:

provider not recognized

我的另一个尝试是 SqlClient:

Imports System.Data.SqlClient

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

Dim myConn As SqlConnection
        myConn = New SqlConnection("Initial Catalog=OutComes; Data Source=localhost;Integrated Security=SSPI;")

        '"Data Source = (LocalDB) \ MSSQLLocalDB;AttachDbFilename=|DataDirectory|\DatabaseInnlogging.mdf;Integrated Security=True")

        '  "Data Source=localhost;Integrated Security=SSPI;")

        'Create a Command object.
        Dim myCmd As SqlCommand
        myCmd = myConn.CreateCommand
        myCmd.CommandText = "SELECT UserID, Password FROM LogInTable"

        'Open the connection.
        myConn.Open()

        Dim results As String
        Dim myReader As SqlDataReader
        myReader = myCmd.ExecuteReader()

        'Traverse the DataSet and Display in GUi for Example:
        Do While myReader.Read()
            results = results & myReader.GetString(0) & vbTab &
                myReader.GetString(1) & vbLf
        Loop
        'Display results.
        MsgBox(results)

        ' Close the reader and the database connection.
        myReader.Close()
        myConn.Close()
End Sub

我的错误是:

System.Data.SqlClient.SqlException: 'A network-related or instance-specific error occurred while connecting to SQL Server. The server was not found or was not available. Verify that the instance name is correct and that SQL Server is configured to accept external connections. (provider: Named Pipes Provider, error: 40 - Unable to open a connection to SQL Server)

我的 SQL 服务器数据库中有一个 table,有两列 UserIDpassword

如果有人能在这里指出正确的方向,我将不胜感激。我已经阅读了很多关于这个主题的 post 但似乎无法找到我哪里出错了。我的主要目标是连接我的数据库。

因为你是新手,你可以尝试一些可视化工具,它可以帮助你看得更清楚,我建议你尝试这种方法,它是你解决方案的一半:

在你的 visual Studio 中:

Menu Tools

Connection to database

在对话框中

Data Source : 微软 SQL 服务器 (sqlClient)

Server Name : ****

你应该在这里找到你的服务器,select它,否则这意味着你的服务器安装有问题

Authentification : Windows 身份验证

我在你的例子中看到你没有使用 SQL id 所以没关系

Connection to database:

Select 你已经创建的数据库,如果没有看到的话 那意味着你没有创建或者你没有访问权限

然后点击按钮Test Connection 如果成功则点击 OK

然后去你的ToolBox

Data

DataGridView 将其放入您的表单中 select 数据源:在底部你会看到 + Add the data source 点击它

您将有一个对话框,选择 Database -> Dataset -> 选择你的数据连接 您应该会在组合框中看到一行 your server name \ your Database.dbo

勾选复选框"Show the connection string saved in the application"

你会清楚地看到你的连接字符串

下一步 -> 下一步 > 检查表格

完成

如果您卡在某个部分,请告诉我通过编辑来澄清您

首先,谢谢 :),我让它工作了。但我还有一些问题。 我从一个新项目开始,用一个 table 创建了一个本地 sqlDB 有两个列“UserID”和“Password”。 我在 table 中有一行带有“Admin”和“pass” 我没有使用 table 设计器或添加数据源。

我完全按照你的描述复制了我的connectionstring到tool connect... 效果很好,我找到了 mdf 文件并能够连接到它

加载了带有数据网格的表单并将其绑定到数据源。它工作正常

然后我尝试在一个新按钮下手动连接到数据库。我收到此错误消息:

System.Data.SqlClient.SqlException: 
'Cannot attach file 'C:\Users\Bruker\source\repos\Connect_v2\Connect_v2\bin\Debug\Database1.mdf' 
as database 'OutComes
' because this file is already in use for database 
'C:\USERS\BRUKER\SOURCE\REPOS\CONNECT_V2\CONNECT_V2\BIN\DEBUG\DATABASE1.MDF''

This was the class:

Imports System.Data.SqlClient

Public Class Form1
   
 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'TODO: This line of code loads data into the 'Database1DataSet.LogInTable' table. You can move, or remove it, as needed.
        Me.LogInTableTableAdapter.Fill(Me.Database1DataSet.LogInTable)

    End Sub

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

        Dim myConn As SqlConnection
        myConn = New SqlConnection("Initial Catalog=OutComes; Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;Connect Timeout=30")



        'Create a Command object.
        Dim myCmd As SqlCommand
        myCmd = myConn.CreateCommand
        myCmd.CommandText = "SELECT UserID, Password FROM LogInTable"

        'Open the connection.
        myConn.Open()

        Dim results As String
        Dim myReader As SqlDataReader
        myReader = myCmd.ExecuteReader()

        'Traverse the DataSet and Display in GUi for Example:
        Do While myReader.Read()
            results = results & myReader.GetString(0) & vbTab &
                myReader.GetString(1) & vbLf
        Loop
        'Display results.
        MsgBox(results)

        ' Close the reader and the database connection.
        myReader.Close()
        myConn.Close()
    End Sub

我试图注释掉加载事件,它手动连接到数据库。它奏效了:)

Imports System.Data.SqlClient


Public Class Form1


    'Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    '    'TODO: This line of code loads data into the 'Database1DataSet.LogInTable' table. You can move, or remove it, as needed.
    '    Me.LogInTableTableAdapter.Fill(Me.Database1DataSet.LogInTable)

    'End Sub

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

        Dim myConn As SqlConnection
        myConn = New SqlConnection("Initial Catalog=OutComes; Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;Connect Timeout=30")



        'Create a Command object.
        Dim myCmd As SqlCommand
        myCmd = myConn.CreateCommand
        myCmd.CommandText = "SELECT UserID, Password FROM LogInTable"

        'Open the connection.
        myConn.Open()

        Dim results As String
        Dim myReader As SqlDataReader
        myReader = myCmd.ExecuteReader()

        'Traverse the DataSet and Display in GUi for Example:
        Do While myReader.Read()
            results = results & myReader.GetString(0) & vbTab &
                myReader.GetString(1) & vbLf
        Loop
        'Display results.
        MsgBox(results)

        ' Close the reader and the database connection.
        myReader.Close()
        myConn.Close()
    End Sub
End Class

这很好,但我仍然想知道为什么我会收到错误消息。是因为 datagridview table 适配器保持与数据库的持续打开连接。并且不可能同时打开多个连接?