I am trying to create a login window with MDI. It is connected to a SQL Server table test. I have changed the datatypes and deleted and recreated the DB. I have 2 columns: usr and pwd of datatype nvarchar.
Dim connetionString As String
Dim cnn As SqlConnection
connetionString = "Data Source=.;Initial Catalog=test;User ID=sa;Password=sasql"
cnn = New SqlConnection(connetionString)
Dim cmd As SqlCommand
Dim myreader As SqlDataReader
Dim query As String
query = "Select usr From users WHERE (usr =" + TextBox1.Text + " and pwd = " + TextBox2.Text + ")"
cmd = New SqlCommand(query, cnn)
cnn.Open()
myreader = cmd.ExecuteReader()
If myreader.Read() Then
Else
MessageBox.Show("Incorrect username/password !", "LOGIN ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
cnn.Close()
Thank you so much.
If you are using Tortuga.Chain, the code would look like this:
Dim ds As New SqlServerDataSource(connetionString)
Dim user = ds.From("users", new With {.usr = TextBox1.Text, .pwd = TextBox2.Text}).ToString.Execute();
If user Is Not Nothing Then
Else
MessageBox.Show("Incorrect username/password !", "LOGIN ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
If you want to stick to raw ADO.NET code, you need to use a parameterized query.
Dim connetionString As String
Dim cnn As SqlConnection
connetionString = "Data Source=.;Initial Catalog=test;User ID=sa;Password=sasql"
cnn = New SqlConnection(connetionString)
Dim cmd As SqlCommand
Dim myreader As SqlDataReader
Dim query As String
query = "Select usr From users WHERE (usr = #user and pwd = #pwd )"
cmd = New SqlCommand(query, cnn)
cmd.Parameters.AddWithValue( "#usr", TextBox1.Text)
cmd.Parameters.AddWithValue( "#pwd", TextBox2.Text)
cnn.Open()
myreader = cmd.ExecuteReader()
If myreader.Read() Then
Else
MessageBox.Show("Incorrect username/password !", "LOGIN ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
cnn.Close()
Remove the spaces from the value of connectionString.
Your query compares textual data, which is invalid unless the user enters ' at the start and end of the textboxes. This would be syntactically correct:
"Select usr From users WHERE (usr ='" + TextBox1.Text + "' and pwd = '" + TextBox2.Text + "')"
but logically flawed, since the user might attempt to inject malicious SQL into your textboxes. Your application is extremely unsafe. You must protect it against SQL injection and you need to encrypt the password of the user as well.
Related
I've been trying to insert data into my sql database but this problem always show up
i've tried redoing it again and the same problem occurs and i'm really stumped right now
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim conn As SqlConnection = New SqlConnection("Data Source=DESKTOP-OBQR58O\SQLEXPRESS;Initial Catalog=Accounts;Integrated Security=True")
Dim comm As SqlCommand = New SqlCommand("insert into User(username, password)values('" + TextBox1.Text + "', '" + TextBox3.Text + "')", conn)
Dim data As SqlDataAdapter = New SqlDataAdapter(comm)
Dim user = TextBox1.Text
Dim pass = TextBox2.Text
Dim cpass = TextBox3.Text
Dim reader As SqlDataReader
conn.Open()
Dim cmd As SqlCommand = New SqlCommand("select Username from [User] where Username ='" + TextBox1.Text + "'", conn)
conn.Close()
conn.Open()
reader = cmd.ExecuteReader
If user.Trim() = "" Or pass.Trim() = "" Or cpass.Trim() = "" Then
MessageBox.Show("Empty Fields", "Blank Spaces")
ElseIf Not String.Equals(pass, cpass) Then
MessageBox.Show("Passwords do not match", "ERROR")
conn.Close()
ElseIf reader.HasRows Then
MessageBox.Show("Username already exists!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
TextBox1.Clear()
conn.Close()
reader.Close()
Else
MessageBox.Show("Account created succesfully!", "Success")
Dim table As DataTable = New DataTable()
data.Fill(table) ' this is where the problem occurs.
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
Dim log As New Login
Me.Close()
log.Show()
conn.Close()
End If
conn.Close()
End Sub
I honestly don't know what to do
You open your reader up at the top:
reader = cmd.ExecuteReader
So, it's open. And then, when you run the Fill command, it conflicts with the open reader!
The simplest fix - although, personally, I would restructure the code a bit, to bring the OpenReader nearer to where it is used - would be to add a Close to your reader right before the Fill.
Else
reader.Close() ' what you would add
MessageBox.Show("Account created succesfully!", "Success")
Dim table As DataTable = New DataTable()
data.Fill(table) ' this is where the problem occurs.
VERY IMPORTANT: If you're not familiar with the concept of "SQL Injection Attacks", read up on them, right away. You should NEVER execute SQL that's been built by constructing a string with unvalidated data from the user. You should pass parameters instead.
After all, what if I typed in the user name of "Irrelevant';DROP TABLE Users;--"? You'd wind up with a SQL Statement that contained "SELECT Username from [Users] WHERE [Username] = 'Irrelevant'; DROP TABLE Users; --'"
And, of course, you should validate the input as well, for things like embedded HTML and script! But that's more complicated than just using SQL Parameters.
I'm trying to make a login form.
I've created a database on my server and created the rows username and password.
I then created a root user with root as password.
but I have a problem with the check if the username and password are correct,
I don't know how to give him the 2 rows.
Dim conn = New SqlConnection("Data Source=SRV-SQL;Initial Catalog=prova;User ID=user;Password=user")
Dim sda = New SqlDataAdapter("select count(*) from tblLogin where username ='" + txtUsername.Text + "' and password='" + txtUserPwd.Text + "'", conn)
Dim dt = New DataTable()
sda.Fill(dt)
If (dt.Rows().ToString() = "1") Then
MsgBox("Logged-in successfully")
Else
MessageBox.Show("The username or the password is wrong!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Table:
Comments and explanations in-line.
Private Sub VerifyLogin()
'For the Return Value of the command
Dim RetVal As Integer
' A Using...End Using will ensure that you connectionis closed and disposed event
'it there is an error.
Using conn = New SqlConnection("Data Source=SRV-SQL;Initial Catalog=prova;User ID=user;Password=user")
'You don't need a DataAdapter, just a command
'USE PARAMETERS. Yes, I am yelling :-) Even if you are the only user
'it will save you headaches with syntax.
Using cmd = New SqlCommand("select count(*) from tblLogin where username = #UserName and password= #Password;", conn)
cmd.Parameters.Add("#UserName", SqlDbType.VarChar).Value = txtUsername.Text
cmd.Parameters.Add("#Password", SqlDbType.VarChar).Value = txtUserPwd.Text
'You are only returning one row
'ExecuteScalar returns the value in the first column of the
'first row of the the data
conn.Open()
RetVal = CInt(cmd.ExecuteScalar)
End Using
End Using
'No need to convert to a string just compare the Integer
If RetVal = 1 Then
MsgBox("Logged-in successfully")
Else
MessageBox.Show("The username or the password is wrong!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End Sub
Private Function CalculateHash(password As String, salt As String) As String
'TODO:
' Suggest pulling the BCrypt from the NuGet gallery for this:
' https://www.nuget.org/packages/BCrypt-Official/
' Just remember that bcyrpt lib encodes salt as part of the password hash, so the function signatures and db table will be different.
End Function
Public Function CheckCredentials(UserName As String, Password As String) As Boolean
Using conn As New SqlConnection("Data Source=SRV-SQL;Initial Catalog=prova;User ID=user;Password=user"), _
' Need to add a "Salt" column to your table, create a new random salt for each user when you create the user
cmd As New SqlCommand("SELECT Salt, PwdHash FROM tblLogin WHERE username = #Username", conn)
'Parameterized queries or NOTHING. String concatention is NOT OKAY here
cmd.Parameters.Add("#UserName", SqlDbType.NVarChar, 50).Value = UserName
conn.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader()
If Not rdr.Read() Then Return False
Dim Salt As String = rdr("Salt")
Dim PwdHash As String = rdr("PwdHash")
'Compare HASHES, not Passwords
Return PwdHash = CalculateHash(Password, Salt As String)
End Using
End Using
End Function
If CheckCredentials(txtUsername.Text, txtUserPwd.Text) Then
MsgBox("Logged-in successfully")
Else
MessageBox.Show("The username or the password is wrong!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Use DataReader instead, use this code and just call CheckLogin in login button or somthing else.
Sub CheckLogin()
Dim conn = New SqlConnection("Data Source=SRV-SQL;Initial Catalog=prova;User ID=user;Password=user")
conn.Open()
Try
Dim query As String = "select count(*) from tblLogin where username = #username and password= #password "
Dim cmd = New SqlCommand(query, conn)
cmd.Parameters.AddWithValue("#username", txtUsername.Text)
cmd.Parameters.AddWithValue("#password", txtUserPwd.Text)
Dim DR As SqlDataReader = cmd.ExecuteReader()
If DR.HasRows Then
MsgBox("Logged-in successfully")
Else
MessageBox.Show("The username or the password is wrong!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close()
End Sub
If CbDept_login.Text = "DEPT1" Then
Dim con As New SqlConnection("Data Source=XYZ-PC;Database=DATABASE1;Integrated Security =true")
con.Open()
Dim rs As New SqlCommand("SELECT * FROM TABLE1 WHERE Username=#Username COLLATE SQL_Latin1_General_CP1_CS_AS AND Password=#Password COLLATE SQL_Latin1_General_CP1_CS_AS", con)
Dim UsernameParam As New SqlParameter("#Username", Me.txtUsername.Text)
Dim PasswordParam As New SqlParameter("#Password", Me.txtPassword.Text)
rs.Parameters.Add(UsernameParam)
rs.Parameters.Add(PasswordParam)
Dim sqlRead As SqlDataReader = rs.ExecuteReader
If sqlRead.HasRows Then
If sqlRead.Read = True Then
If sqlRead("UserType") = "Admin" Then
MsgBox("Log in as " + txtUsername.Text, MsgBoxStyle.OkOnly Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Information, "Login Sucess")
frm_Admin.Show()
frm_Admin.LblLogAsAdmin_LCR.Text = txtUsername.Text
Me.Close()
ElseIf sqlRead("UserType") = "Staff" Then
MsgBox("Log in as " + txtUsername.Text, MsgBoxStyle.OkOnly Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Information, "Login Sucess")
frm_User.Show()
frm_User.TblogAsuser.Text = txtUsername.Text
Me.Close()
End If
End If
Else
MsgBox("Please input correct username and password", MsgBoxStyle.OkOnly Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Critical, "Login Failed")
txtPassword.Text = ""
con.Close()
End If
End If
If CbDept_login.Text = "DEPT2" Then
Dim conn As New SqlConnection("Data Source=XYZ-PC;Database=DATABASE2;Integrated Security =true")
conn.Open()
Dim rs As New SqlCommand("SELECT * FROM TABLE2 WHERE Username=#Username COLLATE SQL_Latin1_General_CP1_CS_AS AND Password=#Password COLLATE SQL_Latin1_General_CP1_CS_AS", con)
Dim UsernameParam As New SqlParameter("#Username", Me.txtUsername.Text)
Dim PasswordParam As New SqlParameter("#Password", Me.txtPassword.Text)
rs.Parameters.Add(UsernameParam)
rs.Parameters.Add(PasswordParam)
Dim sqlRead As SqlDataReader = rs.ExecuteReader
If sqlRead.HasRows Then
If sqlRead.Read = True Then
If sqlRead("UserType") = "Admin" Then
MsgBox("Log in as " + txtUsername.Text, MsgBoxStyle.OkOnly Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Information, "Login Sucess")
frm_Admin.Show()
frm_Admin.LblLogAsAdmin_LCR.Text = txtUsername.Text
Me.Close()
ElseIf sqlRead("UserType") = "Staff" Then
MsgBox("Log in as " + txtUsername.Text, MsgBoxStyle.OkOnly Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Information, "Login Sucess")
frm_User.Show()
frm_User.TblogAsuser.Text = txtUsername.Text
Me.Close()
End If
End If
Else
MsgBox("Please input correct username and password", MsgBoxStyle.OkOnly Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Critical, "Login Failed")
txtPassword.Text = ""
conn.Close()
End If
End If
End Sub
Hello, I'm currently facing a problem in my vb project. I'm using visual studio 2012 and SQL server 2012 for my database. I have a login form in which you can access to the different databases just by choosing department name in a combo box and it will check if you input a correct username and password using sqldatareader depends on the username and password value on the database of the department that you choose. Now my problem is when I run it, it will show an error "No source available". maybe my codes are wrong, please help me. thank you in advance. By the way, i put this code on my Login Button.
Hello guys am having issues with my login form for multiple users of my software, below is the complete login button code for the admin
Private Sub btnlogin_Click(sender As System.Object, e As System.EventArgs) Handles btnlogin.Click
If cmbusertype.Text = "" Then
MsgBox("Please select the appropriate Account Type!", vbExclamation, "Account Type")
End If
If cmbusertype.Text = "Admin" Then
Dim Strconn As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\phermacy.mdf;Integrated Security=True;User Instance=True"
Dim Selectcmd As String = "select * from tbl_admin where admin_username = '" + txtusername.Text + "' and password = '" + txtpassword.Text + "'"
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Dim sqlcmd As SqlCommand
sqlconn = New SqlConnection(Strconn)
Try
sqlconn.Open()
Catch ex As Exception
MsgBox("Could not connect to DataBase. Application will close now!", vbCritical, "Database Error")
End
End Try
sqlcmd = New SqlCommand(Selectcmd, sqlconn)
da.SelectCommand = sqlcmd
sqlcmd.Dispose()
sqlconn.Close()
da.Fill(ds)
Matching Admin User Name & Password
If ds.Tables(0).Rows.Count > 0 Then
If txtusername.Text = ds.Tables(0).Rows(0).Item(0) And txtpassword.Text = ds.Tables(0).Rows(0).Item(1) Then
MsgBox("Administrator Log-in Successful.", vbInformation, "Admin Log-in")
Me.Hide()
adminform.Show()
Else
ErrorProvider1.SetError(txtusername, "Invalid User Name.")
ErrorProvider1.SetError(txtpassword, "Invalid Password.")
MsgBox("Invalid Administrator Username or Password.", vbCritical, "Admin Log-in")
End If
Else
ErrorProvider1.SetError(txtusername, "Invalid User name or Password.")
ErrorProvider1.SetError(txtpassword, "Invalid User name or Password.")
ErrorProvider1.SetError(cmbusertype, "Please select the appropriate Account Type")
MsgBox("Invalid Administrator Username or Password.", vbCritical, "Admin Log-in")
End If
End If
End Sub
the code line highlighted is the following
If txtusername.Text = ds.Tables(0).Rows(0).Item(0) And txtpassword.Text = ds.Tables(0).Rows(0).Item(1) Then
and the error is "Conversion from string "admin" to type 'Double' is not valid." am actually new to vb trying to create a login for multiple users, the above part as you can see is just for the admin. Please any help here will be appreciated thanks.
Try this...
Private Sub btnlogin_Click(sender As System.Object, e As System.EventArgs) Handles btnlogin.Click
If cmbusertype.Text = "" Then
MsgBox("Please select the appropriate Account Type!", vbExclamation, "Account Type")
End If
If cmbusertype.Text = "Admin" Then
Dim Strconn As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\phermacy.mdf;Integrated Security=True;User Instance=True"
Dim Selectcmd As String = "select * from tbl_admin where admin_username = #usernme and password = #paswd"
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Dim sqlcmd As SqlCommand
sqlconn = New SqlConnection(Strconn)
Try
sqlconn.Open()
Catch ex As Exception
MsgBox("Could not connect to DataBase. Application will close now!", vbCritical, "Database Error")
End
End Try
sqlcmd = New SqlCommand(Selectcmd, sqlconn)
sqlcmd.parameters.addwithValue("#usernme",txtusername.Text)
sqlcmd.parameters.addwithValue("#paswd",txtpassword.Text)
da.SelectCommand = sqlcmd
sqlcmd.Dispose()
sqlconn.Close()
da.Fill(ds)
I'm trying a new approach for a project that I'm working on and I'm just starting to learn about Access Databases. I using VB.net and my question is: How do you see if a record exists in the table of the database. I thought I had it understood but that is not the case. I'm creating a login and I want it to check if the Username that they typed in exists before it tries to compare what you typed with what's in the database. I see alot of questions on how to do this...but not for VB.net and MS Access
Here's my code:
Imports System.Data.OleDb
Public Class LoginForm1
Dim provider As String
Dim dataFile As String
Dim connString As String
Public myConnection As OleDbConnection = New OleDbConnection
Public dr As OleDbDataReader
Dim Errors As String
Public Sub AccessAccountDatabase()
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Richard\Documents\Visual Studio 2010\Projects\CybSol Journal Database\CybSol Journal Database\cgi-bin\Data.mdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
Errors = ""
Try
myConnection.Open()
Dim str As String
str = "SELECT * FROM Accounts WHERE Username='" & UsernameTxt.Text & "' AND Password='" & PasswordTxt.Text & "'"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
dr.Read()
If UsernameTxt.Text = dr("Username").ToString AndAlso PasswordTxt.Text = dr("Password").ToString Then
Dim Welcome As String = "SELECT * FROM Accounts WHERE Real_Name=" & "Username"
MsgBox("Welcome back " & dr("Real_Name") & "!")
Else
MsgBox("Login Failure")
End If
myConnection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub OkayBtn_Click(sender As System.Object, e As System.EventArgs) Handles OkayBtn.Click
AccessAccountDatabase()
End Sub
End Class
So now my question is... How do you get it to check if a record exists in the database, because when you type in the correct information (The correct username and password that exists in the database) it says welcome and all. But when you type in the wrong Username and/or Password it doesn't work. Without the "Try Catch" statement the program just freezes. With the try catch it states this:
System.InvalidOperationException: No data exists for the row/column.
at System.Data.OleDb.OleDbDataReader.DoValueCheck(Int32 ordinal)
at System.Data.OleDb.OleDbDataReader.GetValue(Int32 ordinal)
at System.Data.OleDb.OleDbDataReader.get_Item(String name)
at CybSol_Journal_Database.LoginForm1.AccessAccountDatabase() in c:\users\richard\documents\visual studio 2010\Projects\CybSol Journal Database\CybSol Journal Database\LoginForm1.vb:line 36
Addition information: line 36 is this: If UsernameTxt.Text = dr("Username").ToString AndAlso PasswordTxt.Text = dr("Password").ToString Then
First problem:
PASSWORD is a reserved keyword in Access. You should encapsulate in square brackets:
"SELECT * FROM Accounts WHERE Username='" & UsernameTxt.Text & _
"' AND [Password]='" & PasswordTxt.Text & "'"
Second problem:
NEVER use string concatenation to create sql text. ALWAYS use parameters
str = "SELECT * FROM Accounts WHERE Username=? AND [Password]=?"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.AddWithValue("user", UserNameTxt.Text)
cmd.Parameters.AddWithValue("pass", PasswordTxt.Text)
dr = cmd.ExecuteReader
Why? look here what could happen if you concatenate strings from user input
Third problem: Test if your command returns rows
If dr.Read() Then
......
End if
I added some Using statements so you don't have to manually close the connections. Also, I parameterized the SQL statement to prevent SQL Injection.
Public Class LoginForm1
Dim provider As String
Dim dataFile As String
Dim connString As String
'Public myConnection As OleDbConnection = New OleDbConnection
'Public dr As OleDbDataReader
Dim Errors As String
Public Sub AccessAccountDatabase()
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Richard\Documents\Visual Studio 2010\Projects\CybSol Journal Database\CybSol Journal Database\cgi-bin\Data.mdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
Errors = ""
Try
Using myConnection As OleDbConnection = New OleDbConnection(connString)
myConnection.Open()
Dim str As String
str = "SELECT * FROM Accounts WHERE Username=#USER AND [Password]=#PWD "
Using cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.AddWithValue("#USER", UsernameTxt.Text)
cmd.Parameters.AddWithValue("#PWD", PasswordTxt.Text)
Using dr As OleDbDataReader = cmd.ExecuteReader
If dr.HasRows Then
dr.Read()
If UsernameTxt.Text = dr("Username").ToString AndAlso PasswordTxt.Text = dr("Password").ToString Then
Dim Welcome As String = "SELECT * FROM Accounts WHERE Real_Name=" & "Username"
MsgBox("Welcome back " & dr("Real_Name") & "!")
Else
MsgBox("Login Failure")
End If
Else
MsgBox("Login Failure")
End If
End Using
End Using
End Using
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub OkayBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OkayBtn.Click
AccessAccountDatabase()
End Sub
End Class
You're on the right track. The OleDbDataReader.Read returns a boolean indicating whether or not it successfully read an existing row. Therefore, you can check to see if it returned True before trying to read the record. For instance:
If dr.Read() Then
If UsernameTxt.Text = dr("Username").ToString AndAlso PasswordTxt.Text = dr("Password").ToString Then
Dim Welcome As String = "SELECT * FROM Accounts WHERE Real_Name=" & "Username"
MsgBox("Welcome back " & dr("Real_Name") & "!")
Else
MsgBox("Login Failure")
End If
End If
Also, I feel I should at least mention that storing a password in plain text is never a good idea.
You don't have to check for the username and password in your code again since if does not match in the database, no rows will be returned.
You can simply do
dr = cmd.ExecuteReader
If dr.HasRows Then
//it matched
Else
//it didn't match. could not log in
End If
Your approach is below if you still want to keep it but it's not necessary
dr = cmd.ExecuteReader
If dr.HasRows Then
dr.Read()
If UsernameTxt.Text = dr("Username").ToString AndAlso PasswordTxt.Text = dr("Password").ToString Then
Else
End If
End If
Use the Read() method on your DataReader (note that this keeps your connection to the database open and you'll be unable to execute any other commands on the database while your DataReader is still Reading.
If String.Compare(dr("Username").ToString(), UsernameTxt.Text, true) AndAlso String.Compare(dr("Password").ToString(), PasswordTxt.Text.ToString() Then
' The username and password for the record match
' the input from the login form
ProcessLogin()
Else
' Invalid username or password, send an error
End If