简体   繁体   中英

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. 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

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

The others results in an error:

provider not recognized

My other attempt was with 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. 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)

I have one table in my SQL Server database with two columns UserID and password .

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. 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)

Server Name: ****

you should find your server here, select it, Else that's mean you have problem with your server installation

Authentification: Windows Authentification

as i see in your example your are not using SQL id so that's fine

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

Then Click in button Test Connection if success then click OK

Then go to your ToolBox

Data

DataGridView drop it in your form select data source: in bottom you will see + Add the data source click on it

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

Check in the checkbox "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". I had one line in this table with "Admin" and "pass" I did not use the table designer or add a datasource.

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

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. And is not possible to have multiple open connections at the same time?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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