How to update the account table? - vb.net

I need help with my update query. I need to finish this by tomorrow. I think my codes are wrong.
My form:
My database:
My code:
'user wants to change password
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As New OleDbConnection
connection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\db1.accdb;Persist Security Info=True")
Try
connection.Open()
Dim command As OleDbCommand = connection.CreateCommand
command.CommandType = CommandType.Text
command.CommandText = "Update UserAccount SET Password ='" + TextBox2.Text + "' WHERE Username = User"
command.ExecuteNonQuery()
MsgBox("Updated")z
TextBox2.Text = ""
TextBox3.Text = ""
Catch ex As Exception
MsgBox(ex.Message)
End Try

Common mistake. The problem is here:
... WHERE Username = User"
It's looking for a field named User.
Is the username actually User? If so, wrap it in quotes:
... WHERE Username = 'User'"
Is User actually a variable holding the username? If so:
... WHERE Username = '" & User & "'"

Related

a beginner in vb.net.. working on a login form

Imports MySql.Data.MySqlClient
Public Class Form1
Dim cmd As New MySqlCommand
Dim da As New MySqlDataAdapter
Dim con As MySqlConnection = JOKENCONN()
Public Function JOKENCONN() As MySqlConnection
Return New MySqlConnection("server=localhost; user id=root; password=; database =studentdb")
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
GroupBox1.Enabled = False
End Sub
Private Sub LBLLOGIN_CLICK(sender As Object, e As EventArgs) Handles lbllogin.Click
lbllogin.Text = "Login"
lbllogin.Text = "Login"
lblname.Text = "Hi, Guest"
If lbllogin.Text = "Login" Then
GroupBox1.Enabled = True
End If
End Sub
Private Sub BTNOK_CLICK(sender As Object, e As EventArgs) Handles btnok.Click
Dim Sql As String
Dim publictable As New DataTable
Try
If txtusername.Text = "" And txtpass.Text = "" Then
MsgBox("Password or username is incorrect!")
Else
Sql = "select ' from tbluseraccount where username='" & txtusername.Text & "' and userpassword='" & txtpass.Text & "'"
With cmd
.Connection = con
End With
da.SelectCommand = cmd
da.Fill(publictable)
If publictable.Rows.Count > 0 Then
Dim user_type As String
user_type = publictable.Rows(0).Item(4)
Name = publictable.Rows(0).Item(1)
If user_type = "Admin" Then
MsgBox("Welcome " & Name & "you login as Administrator")
lbllogin.Text = "logout"
lblname.Text = "Hi, " & Name
GroupBox1.Enabled = False
txtusername.Text = ""
txtpass.Text = ""
ElseIf user_type = "cetakoradi2" Then
MsgBox("Welcome " & Name & "you login as cetakoradi2")
lbllogin.Text = "logout"
lblname.Text = "Hi, " & Name
GroupBox1.Enabled = False
txtusername.Text = ""
txtpass.Text = ""
Else
End If
Else
MsgBox("contact administrator to register")
txtusername.Text = ""
txtpass.Text = ""
End If
da.Dispose()
End If
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
End Class
this the error i received
ExecuteReader CommandText property has not been properly initialized
i really need help on that. this is the error that i receives. thank you
Assuming that the name of the field represented in publictable.Rows(0).Item(4) is named user_type, then you could use the following:
'Declare the object that will be returned from the command
Dim user_type As String
'Declare the connection object
Dim con As OleDbConnection
'Wrap code in Try/Catch
Try
'Set the connection object to a new instance
con = JOKENCONN()
'Create a new instance of the command object
Using cmd As OleDbCommand = New OleDbCommand("SELECT user_type FROM tbluseraccount WHERE username=#0 AND userpassword=#1;", con)
'Paramterize the query
cmd.Parameters.AddWithValue("#0", txtusername.Text)
cmd.Parameters.AddWithValue("#1", txtpass.Text)
'Open the connection
con.Open()
'Use ExecuteScalar to return a single value
user_type = cmd.ExecuteScalar()
'Close the connection
con.Close()
End Using
Catch ex As Exception
'Display the error
Console.WriteLine(ex.Message)
Finally
'Check if the connection object was initialized
If con IsNot Nothing Then
If con.State = ConnectionState.Open Then
'Close the connection if it was left open(exception thrown)
con.Close()
End If
'Dispose of the connection object
con.Dispose()
End If
End Try
If (String.IsNullOrWhitespace(user_type)) Then
'Failed login
ElseIf (user_type = "Admin") Then
'Admin login
ElseIf (user_type = "cetakoradi2") Then
'cetakoradi2 login
Else
'Not a failed login, but also not an admin or cetakoradi2 either
End If
What this code does is setup a parameterized query to get just the user_type where the username and password match the parameterized values. Since there should only ever be one record that matches those conditions (presumably) then we're able to use ExecuteScalar to return just that single field value.
Just to reinforce the point, MySqlCommand.ExecuteScalar, just like the Microsoft counterparts, "executes the query, and returns the first column of the first row in the result set returned by the query. Extra columns or rows are ignored" and returns " The first column of the first row in the result set, or a null reference if the result set is empty ".
The proposed code by #David checks for this condition using IsNullOrWhitespace.
ExecuteScalar is effective but retrieves only one value at a time.
The other option pursued by the OP is to return a datarow, which is a valid approach if he wants to return several fields at the same time. In his example he retrieves two fields for variables user_type and Name respectively.
Be careful, VB.net like any other programming language has reserved keywords. If you do not take a habit of using good naming conventions you might one day stumble upon on one of those keywords, possibly hit obscure bugs. Name is not a good name for a variable and has the potential for confusion since every object has a name property.
To address the specific issue at hand, the error message ExecuteReader CommandText property has not been properly initialized is self-explanatory. What should have been done is simply:
With cmd
.Connection = con
.CommandText = Sql
End With
You defined a command, but did not tell it what to do. In your code variable Sql is defined but unused. With this missing bit there is a chance the code will work as expected.
Small details:
Not critical, but his condition does not work if you enter whitespace for example:
If txtusername.Text = "" And txtpass.Text = "" Then
An improvement is to simply trim the values from the textboxes:
If txtusername.Text.Trim = "" And txtpass.Text.Trim = "" Then
But I think what you want is not an And but Or. I don't think you want to allow logins without passwords.
Instead of doing multiple If/ElseIf you could have a Select Case

Multiple User Registration Form vb.net

I have a user registration form for multiple users. This works fine except the code is unable to identify if there is already username exist. I know there is mistake in my code but I am unable to rectify that one.
Code is below can anyone help me sort this, how to write modify code for reader
Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click
Dim user, pass As String
user = UsernameTextBox.Text
pass = PasswordTextBox.Text
Dim connection1 As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Credentials.mdb;")
Dim command As New OleDbCommand("SELECT [ID] FROM [Staff] WHERE [usernameField] = username AND [passwordField] = password", connection1)
Dim usernameParam As New OleDbParameter("username", Me.UsernameTextBox.Text)
Dim passwordParam As New OleDbParameter("password", Me.PasswordTextBox.Text)
command.Parameters.Add(usernameParam)
command.Parameters.Add(passwordParam)
command.Connection.Open()
Dim reader As OleDbDataReader = command.ExecuteReader()
If reader.HasRows Then
MessageBox.Show("User Exist")
MyPlayer.SoundLocation = path & LogOnsound
PasswordTextBox.Text = ""
UsernameTextBox.Text = ""
ElseIf user = "" Or pass = "" Then
MsgBox("Please Fill The Boxs", , "Error")
Else
Dim connection As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Credentials.mdb;"
Using myconnection As New OleDbConnection(connection)
myconnection.Open()
Dim sqlq As String = "INSERT INTO [staff] ([username], [password]) VALUES (#user, #pass)"
Using cmd As New OleDbCommand(sqlq, myconnection)
cmd.Parameters.AddWithValue("#usernme", user)
cmd.Parameters.AddWithValue("#passwrd", pass)
cmd.ExecuteNonQuery()
MsgBox("User Registered!", , "register")
user = ""
pass = ""
End Using
End Using
End If
command.Connection.Close()
End Sub
It looks like you have multiple things wrong:
You should be specifying #username instead of just username in your SELECT statement so that it will be recognized as a parameter.
Why are you checking for a match on password also? If you do that, people can have the same username with just a different password...do you want that?
In your SELECT, you have usernameField as the column name in your Staff table, but in your INSERT, you have username as the column name. Which is it?
In your INSERT, you specify the parameter #user, but in your cmd.Parameters.AddWithValue statement, you have #usernme.

How to make log in code in vb.net

Hello Guys please help me about this code,
This is simple log in code in visual studio 2013, my problem is, i try to make wrong password and user name, but the message box does not shows, it means no event after the "else"
HERE IS MY CODE:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnEnter.Click
Dim dr As OleDbDataReader
Call OpenDB()
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM smcUser WHERE UserName = '" & txtTeacher.Text & "'AND UserPass ='" & txtPword.Text & "'")
cmd.Connection = conn
dr = cmd.ExecuteReader
If dr.HasRows = True Then
dr.Read()
If dr.Item("UserName") = txtTeacher.Text And dr.Item("UserPass") = txtPword.Text Then
frmMain.Show()
Me.Hide()
Else
MsgBox("You are not a Registered Teacher")
End If
End If
dr.Close()
frmMain.StatusStrip1.Items(0).Text = txtTeacher.Text
Call CloseDB()
End Sub
Your issue is that your query "SELECT * FROM smcUser WHERE UserName = '" & txtTeacher.Text & "'AND UserPass ='" & txtPword.Text & "'" does not return anything when you enter the wrong password, so it never even executes the code within the If dr.HasRows = True Then block.
Also, you should NEVER store passwords in plain text. Hash them. And, you should always use parameters to preclude SQL injection attacks.
So, you would want to change your code to something like this:
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM smcUser WHERE UserName = #UserName AND UserPass = #HashedPassword")
cmd.Parameters.Add(New OleDbParameter("#UserName", txtTeacher.Txt))
cmd.Parameters.Add(New OleDbParameter("#HashedPassword", HasherFunction(txtPword.Txt)))
Note the addition of the parameters and also the HasherFunction which you would have to build to hash your password accordingly.
There are plenty of resources available about SQL injection and how to avoid it. Here's one I found at the top of the Google search: https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
you almost there in your code, just don't repeat the checking if the user exists in the database, and you code should be like this based on what you put in the question
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnEnter.Click
Dim dr As OleDbDataReader
Call OpenDB()
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM smcUser WHERE UserName = '" & txtTeacher.Text & "'AND UserPass ='" & txtPword.Text & "'")
cmd.Connection = conn
dr = cmd.ExecuteReader
If dr.HasRows = True Then
' you don't need to check again if the user and password are same since you made it
' in you query to database
frmMain.Show()
Me.Hide()
Else
MsgBox("You are not a Registered Teacher")
End If
dr.Close()
frmMain.StatusStrip1.Items(0).Text = txtTeacher.Text
Call CloseDB()
End Sub
hope it will help you

VB Login form ASP.NET with membership or similar

need some minor help with declaring a new array that could read the sql username of the user (if logged in) and store it for later use, either to use it for pages that only authorized users could see (with simple if commands) or lockdown the whole site with web.config authorization system that would allow roles only for admins.
My code is this
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
If Page.IsValid Then
' check for username & password in the database
Dim conn As New SqlConnection("Data Source=.;Initial Catalog=SoftCoD;User ID=sa;Password=fouf")
' Get the row corresponding the given username and password
Dim strSQL As String = "Select * From users Where Name='" + txtUname.Text + "' and Password = '" + txtPassword.Text + "'"
'I recommend not to use * in querys
Dim dsc As New SqlClient.SqlCommand(strSQL, conn)
conn.Open()
Dim dr As SqlDataReader
dr = dsc.ExecuteReader()
If dr.HasRows = True Then
dr.Read()
*g_sUser=Name????MsgBox(g_sUser)*
Response.Redirect("Default.aspx")
Else
Response.Redirect("login.aspx")
End If
conn.Close()
End If
End Sub
You can use any of the following method for holding the username for future use
Session
QueryString
Method 1 : Session
dr = dsc.ExecuteReader()
If dr.HasRows = True Then
dr.Read()
session("user")= g_sUser
Response.Redirect("Default.aspx")
Else
Response.Redirect("login.aspx")
End If
Method 2 : QueryString
dr = dsc.ExecuteReader()
If dr.HasRows = True Then
dr.Read()
Response.Redirect("Default.aspx?username=g_sUser")
Else
Response.Redirect("login.aspx")
End If

login in vb.net and sql server 2008

How I'm going to redirect to another page after login is successful ?
and how I'm going to check if the username & password are correct or not ?
this is my code for login :
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnlogin.Click
If txtUser.Text = "" Then
MsgBox("Please Enter The Username !", MsgBoxStyle.OkOnly)
ElseIf txtPass.Text = "" Then
MsgBox("Please Enter The Password !", MsgBoxStyle.OkOnly)
End If
Dim connectionString As String = "server=''; user id=''; password=''; Database=''"
Dim conLogin As SqlClient.SqlConnection = New SqlClient.SqlConnection(connectionString)
Dim queryString As String = "SELECT login VALUES " _
& "(#username, #password) "
You need to learn SQL first: The following statement is not correct SQL.
SELECT login VALUES (#username, #password)
The statement should look like this:
SELECT * FROM Login WHERE UserName = #username AND Password = #password
Then you need to set the command parameters #username and #password.
I also doubt that the connection string you're using is correct. Use an SqlConnectionStringBuilder to create a correct connection string. In addition, you do not open the connection, so there's not database access possible.
To redirect to another page, see code below
response.redirect("abc.apsx")
You can also use datareader and this sql query
Select count(*) from Login where UserName = #username and Password = #password
if (dr > 0) {
response.redirect('home');
}
else{
//error message
}
just search about datareader.......
...Hope it helps...
Here is the complete code for Login Function.
For more details visit my blog : http://uncopyrightables2011.blogspot.com/
or Tweet me : #MaxRohana
Private Sub btnlogin_Click(sender As System.Object, e As System.EventArgs) Handles btnlogin.Click
ConnectToSQL()
End Sub
Private Sub ConnectToSQL()
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim Passowrd As String
Dim Passowrd2 As String
Dim userName As String
Try
If
'change the data source and initial catalog according to your sql server engine and data base
con.ConnectionString = "Data Source = YOUR-PC; Initial Catalog = YOUR-DB; Integrated Security = True"
con.Open()
cmd.Connection = con
'change the data fields names and table according to your database
cmd.CommandText = " SELECT UserName, Password FROM AdminDetail WHERE (UserName = '" & txtUsername.Text & "' ) AND (Password = '" & txtPassword.Text & "')"
Dim lrd As SqlDataReader = cmd.ExecuteReader()
If lrd.HasRows Then
While lrd.Read()
'Do something here
Passowrd = lrd("Password").ToString()
userName = lrd("UserName").ToString()
Passowrd2 = txtPassword.Text()
If Passowrd = Passowrd2 And userName = txtUsername.Text Then
MessageBox.Show("Logged in successfully as " & userName, "", MessageBoxButtons.OK, MessageBoxIcon.Information
)
frmMain.Show()
Me.Hide()
'Clear all fields
txtPassword.Text = ""
txtUsername.Text = ""
End If
End While
Else
MessageBox.Show("Username and Password do not match..", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
'Clear all fields
txtPassword.Text = ""
txtUsername.Text = ""
End If
End If
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection.
End Try
End Sub