简体   繁体   English

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

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

I can't understand why I can't connect with my SQL Server Express LocalDB.我不明白为什么我无法连接到我的 SQL Server Express LocalDB。 I keep getting in to trouble with my connection string.我不断遇到连接字符串的麻烦。 This is what I have tried:这是我尝试过的:

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

I have tried several connection strings, but none is working.我尝试了几个连接字符串,但没有一个有效。

But with the number 4, I got error但是对于数字 4,我得到了错误

Multiple-step OLE DB operation generated errors.check each OLE DB status value多步 OLE DB 操作产生错误。请检查每个 OLE DB 状态值

The others results in an error:其他导致错误:

provider not recognized供应商不被认可

My other attempt was with SqlClient :我的另一个尝试是使用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

My error here was:我的错误是:

System.Data.SqlClient.SqlException: 'A network-related or instance-specific error occurred while connecting to SQL Server. System.Data.SqlClient.SqlException:'连接到 SQL 服务器时发生与网络相关或特定于实例的错误。 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.验证实例名称是否正确,以及 SQL 服务器是否配置为接受外部连接。 (provider: Named Pipes Provider, error: 40 - Unable to open a connection to SQL Server) (提供者:命名管道提供者,错误:40 - 无法打开与 SQL 服务器的连接)

I have one table in my SQL Server database with two columns UserID and password .我的 SQL 服务器数据库中有一张表,其中包含两列UserIDpassword

I would be very grateful if someone could point me in the right direction here.如果有人能在这里指出正确的方向,我将不胜感激。 I have read many post on the subject but cant seem to find where I go wrong.我已经阅读了很多关于这个主题的帖子,但似乎找不到我 go 错误的地方。 My main goal here is to connect with my database.我的主要目标是连接我的数据库。

As you are new you can try some visual tools it can help you to see more clear, I suggest you to try this approach, it's a half way to your solution:由于您是新手,您可以尝试一些可视化工具,它可以帮助您看得更清楚,我建议您尝试这种方法,这是您解决方案的一半:

In your visual Studio:在您的视觉工作室中:

Menu Tools

Connection to database

In the Dialog在对话框中

Data Source: Microsoft SQL Server (sqlClient) Data Source: Microsoft SQL 服务器(sqlClient)

Server Name: **** Server Name: ****

you should find your server here, select it, Else that's mean you have problem with your server installation你应该在这里找到你的服务器,select 它,否则这意味着你的服务器安装有问题

Authentification: Windows Authentification Authentification: Windows 认证

as i see in your example your are not using SQL id so that's fine正如我在您的示例中看到的那样,您没有使用 SQL id,所以没关系

Connection to database:

Select the Database that you already created, if nothing seen that's mean you didn't created or you don't have rights to access Select 您已经创建的数据库,如果没有看到这意味着您没有创建或您没有访问权限

Then Click in button Test Connection if success then click OK然后单击按钮Test Connection如果成功然后单击OK

Then go to your ToolBox然后 go 到你的ToolBox

Data

DataGridView drop it in your form select data source: in bottom you will see + Add the data source click on it DataGridView把它放到你的表格 select 数据源:在底部你会看到+ Add the data source点击它

You will have a Dialog, choose Database -> Dataset -> choose you data connection you should see a line in the combobox with your server name \ your Database.dbo您将有一个对话框,选择Database -> Dataset -> 选择您的数据连接,您应该会在 combobox 中看到一行,其中包含your server name \ your Database.dbo

Check in the checkbox "Show the connection string saved in the application"选中复选框"Show the connection string saved in the application"

you will see clearly your connection string你会清楚地看到你的连接字符串

Next -> Next > check Tables下一步 -> 下一步 > 检查表格

Finish结束

If you stuck in some part let me know to clarify you by an Edit如果您卡在某个部分,请告诉我通过编辑来澄清您

First of all, THANK YOU:), I got it to work.首先,谢谢你:),我让它工作了。 But I still have som questions.但我还有一些问题。 I started with a fresh project and made a local sqlDB with one table with two columbs "UserID" and "Password".我从一个新项目开始,并制作了一个本地 sqlDB,其中一个表有两个列“UserID”和“Password”。 I had one line in this table with "Admin" and "pass" I did not use the table designer or add a datasource.我在此表中有一行带有“Admin”和“pass”我没有使用表设计器或添加数据源。

I followed your description to the letter and copied my connectionstring under tool connect... That worked fine and I found the mdf file and was able to connect to it我按照您对信件的描述并在工具连接下复制了我的连接字符串...效果很好,我找到了 mdf 文件并能够连接到它

Loaded the form with a datagrid and bound it to the datasource.使用数据网格加载表单并将其绑定到数据源。 It worked properly它工作正常

Then I tried to connect to the DB under a new button manualy.然后我尝试手动连接到新按钮下的数据库。 I got this error message:我收到此错误消息:

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

I tried to comment out the load event and It connected with the DB manualy.我试图注释掉加载事件并手动连接到数据库。 It worked:)有效:)

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

This is great but I still wonder why I got the error message.这很好,但我仍然想知道为什么我收到错误消息。 Is it because the datagridview tableadapter holds a constanctly open connection to the DB.是不是因为 datagridview tableadapter 拥有与数据库的持续打开连接。 And is not possible to have multiple open connections at the same time?并且不可能同时有多个打开的连接?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM