Concatenate database query result to a string - sql

I am trying to take the single result from a SQL query and concatenate it to a string. Using SQL Server and Visual Studios.
Dim Password As SqlDataReader
cmd.CommandText = "Select Password from tblLogin where Username = '" & UsernameTextBox.Text & "' and EmailAddress = '" & EmailAddressTextBox.Text & "'"
Password = cmd.ExecuteReader
EmailMessage.Body = ("Your password is: " & Password)
The error I am getting is that I cannot use the operator & with Password.

The Password variable in your code is a SQLDataReader object, not a string. It can have many values, so you need to get the part you want out of it. (https://msdn.microsoft.com/en-us/library/haa3afyz(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2)
If Password.HasRows Then
Do While Password.Read()
EmailMessage.Body = ("Your password is: " & Password.GetString(0))
Loop
Else
Console.WriteLine("No rows found.")
End If
I would also recommend changing the Password SQLDataREader to a different name, just to make it less confusing.

Related

Using case-sensitive SELECT query for login module

I am developing a Windows Form application using vb.net in VS10 with user management. I am using following code when a user tries to login:
Try
Dim sel As String
sel = "SELECT uid, name, loginid, password, type FROM user_master WHERE loginid = '" & UsernameTextBox.Text & "' AND password = '" & PasswordTextBox.Text & "'"
Dim cnn As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\RSMS_DB.mdf;Integrated Security=True;User Instance=True")
Dim da As New SqlDataAdapter(sel, cnn)
Dim ds As New DataSet()
da.Fill(ds)
If ds.Tables(0).Rows.Count = 0 Then
MsgBox("Wrong Username and Password Combination!", MsgBoxStyle.Critical, "Login Failed")
Else
current_uid = ds.Tables(0).Rows(0)(0)
current_name = ds.Tables(0).Rows(0)(1)
current_loginid = ds.Tables(0).Rows(0)(2)
current_password = ds.Tables(0).Rows(0)(3)
current_type = ds.Tables(0).Rows(0)(4)
MsgBox("Welcome '" & ds.Tables(0).Rows(0)(1) & "'!", MsgBoxStyle.OkOnly, "Login Successful")
Dim upd = "UPDATE user_master SET lastlogin = '" & System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") & "' WHERE uid = " & current_uid & ""
Dim cmd As New SqlCommand(upd, cnn)
cnn.Open()
cmd.ExecuteNonQuery()
If checkboxLoginState.Checked = True Then
cmd.CommandText = "INSERT INTO login_state VALUES('" & current_uid & "', '" & current_name & "', '" & current_loginid & "', '" & current_password & "', '" & current_type & "')"
cmd.ExecuteNonQuery()
End If
cnn.Close()
load_user_permissions(current_uid) 'DISABLING OPTIONS ACCORDING TO USER RIGHTS
Me.Close()
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Database Error")
End Try
All I want to ask is if it is the right method? Is the SELECT Query case sensitive by default?
The SQL Keywords are case-insensitive (SELECT, FROM, WHERE, etc), but are often written in all caps. However in some setups table and column names are case-sensitive. Usually case-sensitive table and column names are the default. If you want to change it then you can change it in a function of the database's collation settings.
Source - And this could also be helpful for you.
If security is important to you then you should hash the passwords - do not save passwords as plain text! You should check out the library libsodium

How do I get a login form to reject entries with wrong capitalization?

I have the following code so far for a login form taking data from a database:
Dim myconnection As New SqlConnection("server=classified;database=classified")
myconnection.Open()
Dim theQuery As String = " SELECT Username, Password FROM Accounts WHERE (Username = '" & TextBox1.Text & "' ) AND (Password = '" & TextBox2.Text & "')"
Dim repeatChecker As SqlCommand = New SqlCommand(theQuery, myconnection)
'mycommand.ExecuteNonQuery()
Using reader As SqlDataReader = repeatChecker.ExecuteReader()
If reader.HasRows Then
' User already exists
While reader.Read()
If reader("Password") = TextBox2.Text.ToString And reader("Username").ToString = TextBox1.Text Then
MessageBox.Show("Logged in successfully as " & TextBox1.Text, "", MessageBoxButtons.OK, MessageBoxIcon.Information)
Firs.Show()
Me.Close()
'Clear all fields
End If
End While
Else
MessageBox.Show("Invalid username or password.", MsgBoxStyle.Critical)
End If
End Using
myconnection.Close()
If I put in the correct login info but with wrong capitalization, I don't get an acceptance or a rejection, the program just sits there and does nothing. How can I get a denial of a login when the capitalization is wrong?
As written, you really can't discern just a case-mismatch from a query as you've illustrated in this code. If a database is set up for case-sensitivity, a query will fail if two strings don't match even for the difference of a single mismatched character, but it doesn't retain that as a reason for the mismatch anymore than it would for, say "Apple" not matching "Banana."
Please note that, as the commentators of your question stated:
You're vulnerable to SQL-Injection attacks.
You should never store passwords in clear text in your DataBase. Once the DB gets cracked, all credentials are compromised. Not to mention evil DB-admins that might get tempted to misuse those credentials...
Case-Sensitivity in a password is a good thing.
With those things mentioned, if you want to provide your users with the comfort of a not case-sensitive username, just cast the TextBox1.Text as well as the query result for the Username to upper case by changing (Username = '" & TextBox1.Text & "' ) to (UPPER(Username) = '" & TextBox1.Text.ToUpper() & "')

Save query results as a string vb.net

I am creating a forgot password feature for a login form. If the users username and email match whats in the database then an email containing their password needs to be sent to their email address. Once my select statements grabs the password I do not know how to convert that over into the body of the email.
cmd2.CommandText = "Select Password from tblLogin where Username = '" & UsernameTextBox.Text & "' and EmailAddress = '" & EmailAddressTextBox.Text & "'"
pass = cmd2.ExecuteReader
If pass.HasRows Then
Do While pass.Read()
EmailMessage.Body = "Here is your password:"
Loop
Else
Console.WriteLine("No rows found.")
End If
The only thing I can think of doing is this:
EmailMessage.Body = ("Here is your password: " & pass)
However I still need to figure out how I can convert pass into a string containing the query result.
EmailMessage.Body = "Here is your password: " & pass.Item(0)
Since you only want the one value from the DB, look at ExecuteScalar instead of ExecuteReader.
However, as Alex commented, unencrypted passwords is really not a good idea.

Syntax Error in FROM Clause - MS. Access

Here's the code :
str = "select * from user where username= '" & txtUsername.Text & "' & password = '" & txtPassword.Text & "'"
perintah = New OleDbCommand(str, conn)
reader = perintah.ExecuteReader()
If reader.Read Then
MessageBox.Show("login success")
Else
MessageBox.Show("login failed")
End If
Most likely the immediate issue is that "user" is a reserved word. Not 100% sure about Access but it is in most databases. Try escaping it, i.e. "[user]", and see if that fixes it.
I also just noticed that you are using "&" where "AND" is the operator you need. I believe that "password" is a reserved word too, so escape that also.
You still have other potential issues there too though. Using string concatenation to insert values into SQL code is a recipe for disaster, not only potentially causing syntax errors but, even worse, opening you up to SQL injection. Read this for more information. In this case specifically, do something like this:
str = "SELECT * FROM [user] WHERE username = #username AND [password] = #password"
perintah = New OleDbCommand(str, conn)
perintah.Parameters.Add("#username", OleDbType.VarChar, 50).Value = txtUsername.Text
perintah.Parameters.Add("#password", OleDbType.VarChar, 50).Value = txtPassword.Text

How to Update Password

I'm trying to change a password. Can you look for this and tell what's wrong? Some times I get a Syntax error in the UPDATE statement or even it is working the password didn't change in database. Here's my code:
Dim sqlquery As String = "UPDATE tblLogin SET pword = ? WHERE pword = '" & txtnewpass.Text & "' "
Dim sqlcmd As New OleDbCommand(sqlquery, con)
sqlcmd.Parameters.AddWithValue("#pword", txtnewpass.Text)
con.Open()
sqlcmd.ExecuteNonQuery()
con.Close()
MessageBox.Show("Your password has been changed", "Change Password", MessageBoxButtons.OK, MessageBoxIcon.Information)
Thank you for your help
I don't know VB and VB SQL Syntax by heart, but a Quick Look at your code shows that there are at least two mistakes.
"UPDATE tblLogin SET pword = ?
should be
"UPDATE tblLogin SET pword = #pword
The
WHERE pword = '" & txtnewpass.Text & "' "
should be
WHERE pword = '" & txtoldpass.Text & "' "
Or make it with #param as well. You are trying to change password which doesn't exists yet.
Besides that, passwords should be encrypted in the database, and you shouldn't match (where clause) just by password. What if 2 users have the same password? You will change both user's passwords;)