简体   繁体   中英

vb.net cannot connect to sql server

I am trying to make a login database using vb.net. I am using this code to connect but it doesn't work!:

Public Class Form1
    Private Sub Label2_Click(sender As Object, e As EventArgs) Handles Label2.Click
        Dim con As New SqlConnection
        Dim cmd As New SqlCommand
        Dim rd As SqlDataReader




        con.ConnectionString = "Data Source=localhost; Initial Catalog=user; Integrated Security= true"
        cmd.Connection = con
        con.Open()
        cmd.CommandText = "select login, password from auth where login= '" & TextBox1.Text & "' and password = '" & TextBox2.Text & "' "

        rd = cmd.ExecuteReader
        If rd.HasRows Then
            Welcome.Show()
        Else
            MessageBox.Show("Login Failed", "error")
        End If
    End Sub
End Class

I have a data base on my sql server called "user" and in user there is a table named "dbo.auth". When I click Label2, visual basic says "con cannot be opened" I am using MySQL server workbench. Is there any way I can fix this? The server is also running on my local network.

Does this work for you?

Imports System.Data.SqlClient
Public Class LoginForm1
    Dim conn As SqlConnection
    ' TODO: Insert code to perform custom authentication using the provided username and password 
    ' (See http://go.microsoft.com/fwlink/?LinkId=35339).  
    ' The custom principal can then be attached to the current thread's principal as follows: 
    '     My.User.CurrentPrincipal = CustomPrincipal
    ' where CustomPrincipal is the IPrincipal implementation used to perform authentication. 
    ' Subsequently, My.User will return identity information encapsulated in the CustomPrincipal object
    ' such as the username, display name, etc.

    Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
        conn = New SqlConnection
        conn.ConnectionString = "Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;"
        Try
            conn.Open()
            MsgBox("Connected!")
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
     End Sub

Also, I think you should bookmark the link below.

https://www.connectionstrings.com/

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