Jinx Jinx - 6 months ago 20
Vb.net Question

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

This is my code from my login form.. whenever i run the program and enter my username and password this will happenenter image description here

This is MyConnection.vb that i use to connect to my database
Public Class MYConnection

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


End Class

here is my dbo.User table
enter image description here

Answer

You are missing a ' for string field, but i advise you to use Parameters to avoid SQL injections, like this:

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