连接到 sql 服务器

Connect to sql server

Public Class Form1

    Private Sub btnlogin_Click(sender As Object, e As EventArgs) Handles btnlogin.Click
        Dim con As New SqlClient.SqlConnection(MYConnection.MYconnectionString)
        con.Open()
        Dim dr As SqlClient.SqlDataReader
        Dim cmd As New SqlClient.SqlCommand("select * from [User] where UserName=" + txtuser.Text + " and UserPass= " + txtpassword.Text + "", con)
        dr = cmd.ExecuteReader
        If dr.Read Then
            MsgBox("Welcome")
        End If
        con.Close()

    End Sub
End Class

这是我登录表单中的代码。每当我 运行 程序并输入我的用户名和密码时,都会发生这种情况:

这是我用来连接到我的数据库的MyConnection.vb

Public Class MYConnection

    Public Shared MYconnectionString As String = "Server=CLAIRETUMLOS\SQLEXPRESS;Database=Capstone;Integrated Security=True;"

End Class

这是我的 dbo.User table

您缺少 ' 字符串字段,但我建议您使用参数来避免 SQL 注入,如下所示:

Private Sub btnlogin_Click(sender As Object, e As EventArgs) Handles btnlogin.Click
    Dim con As New SqlClient.SqlConnection(MYConnection.MYconnectionString)
    con.Open()
    Dim dr As SqlClient.SqlDataReader
    Dim cmd As New SqlClient.SqlCommand("select * from [User] where UserName=@UserName and UserPass=@UserPass", con)
    cmd.Parameters.AddWithValue("@UserName", txtuser.Text)
    cmd.Parameters.AddWithValue("@UserPass", txtpassword.Text)
    dr = cmd.ExecuteReader
    If dr.Read Then
        MsgBox("Welcome")
    End If
    con.Close()
End Sub