SqlDataAdapter#Fill: `SelectCommand.connection` property has not been initilized - mysql

I am making a Student Management System for our thesis. When I click the login button after I put the username and password, this error shows up in da.Fill(dt):
InvalidOperationException was unhandled
Fill: SelectCommand.connection property has not been initilized.
Here is my code in login button
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
cs = "Data Source=.\SQLEXPRESS;Initial Catalog=demo;Integrated Security=True"
con = New SqlConnection(cs)
Dim username As String = TextBox1.Text
Dim password As String = TextBox2.Text
cmd = New SqlCommand("select username,password from login where
username='" + TextBox1.Text + "'and password'" + TextBox2.Text + "' ")
da = New SqlDataAdapter(cmd)
dt = New DataTable()
da.Fill(dt)
If (dt.Rows.Count > 0) Then
name = TextBox1.Text
MessageBox.Show("Login Successful", "success!",
MessageBoxButtons.OK, MessageBoxIcon.Information)
content.Show()
Else
MsgBox("Invalid Login Information!", MessageBoxButtons.OK,
MessageBoxIcon.Error)
End If
End Sub
End Class
When I click the login button I should get to the home page.
This is the login:
and this is the home:

You have to specify which connection to use in your command.
cmd = New SqlCommand("select username,password from login where
username='" + TextBox1.Text + "'and password'" + TextBox2.Text + "' ", con)
Please note, you are concatenating string to build your SQL Query. This is VERY unsecure. This lead to SQL Injection! Please at least double quote in string variable, and check int variable that are variable. But I strongly suggest you to use parametrized variable (See sp_executeSql).
cmd = New SqlCommand("select username,password from login where
username='" + TextBox1.Text.replace("'", "''") + "'and password'" + TextBox2.Text.replace("'", "''") + "' ", con)

Comments and explanations in-line.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim cs = "Data Source=.\SQLEXPRESS;Initial Catalog=demo;Integrated Security=True"
Dim Exists As Boolean
'The Using block ensures that your database objects are closed and disposed
'even if there is an error.
Using con = New SqlConnection(cs)
'All you need to know is if the record exists. You do not need to return
'the values you just entered.
'Pass the connection to the constructor of the command
Using cmd = New SqlCommand("If Exists (Select username, password From login Where
username=#User and password = #Password;", con)
'Use parameters. It not only helps protect your database against SQL Injection but
'simplifies your SQL statement
cmd.Parameters.Add("#User", SqlDbType.VarChar).Value = TextBox1.Text
cmd.Parameters.Add("#Password", SqlDbType.VarChar).Value = TextBox2.Text
'You do not need a data adapter or data table for this
'Use execute scalar when you are returning a single value
con.Open()
Exists = CBool(cmd.ExecuteScalar)
End Using
End Using
If Exists Then
Name = TextBox1.Text
MessageBox.Show("Login Successful", "success!", MessageBoxButtons.OK, MessageBoxIcon.Information)
content.Show()
Else
MessageBox.Show("Invalid Login Information!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End Sub
EDIT
Never store passwords as plain text.

Related

Check if record already exists

I am creating a program in VB.NET where, before creating a user I want to check that if that record already exists.
Here is my code:
Imports MySql.Data.MySqlClient
Public Class WindowsAdvancedStudyStartingForms
Dim FirstName As String = ""
Dim SecondName As String = ""
Dim FullName As String = ""
Dim StudentClassReal As String = ""
Dim StudentClassValue As String = ""
Dim Address As String = ""
Dim Username As String = ""
Dim Password As String = ""
Dim SuccessfulMessage As Integer = 0
'MySql
Dim ServerString As String = "Server=myServer;User ID=myID;Passwordmy=Password;Database=myDatabase;SSLMode=None"
Dim SQLConnection As MySqlConnection = New MySqlConnection
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
FirstName = AFirstNameTextBox.Text
SecondName = ASecondNameTextBox.Text
FullName = FirstName + " " + SecondName
StudentClassValue = ASelectClassComboBox.SelectedItem
Address = AAddressTextBox.Text
Username = AUsernameTextBox.Text
Password = APasswordTextBox.Text
If StudentClassValue = "Class IX" Then
StudentClassReal = 9
Else
MessageBox.Show("You have selected a Wrong Class", "Wrong Class", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
If FirstName = "" And FirstName.Count = 1 Then
MessageBox.Show("You didn't enter your First Name", "First Name", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
'Nothing
End If
If SecondName = "" Then
MessageBox.Show("You didn't enter your Second Name", "Second Name", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
'Nothing
End If
If Address = "" Then
MessageBox.Show("You didn't enter your Address", "Address", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
'Nothing
End If
If Username = "" Then
MessageBox.Show("You didn't enter your Username", "Username", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
'Nothing
End If
If Password = "" Then
MessageBox.Show("You didn't enter your Password", "Password", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
'Nothing
End If
If StudentClassReal = "9" Then
Dim StudentInformationVerification As Integer = MessageBox.Show("Are you sure that these are your information?" & vbCrLf & "I am " + FullName + ", and I study at Class " + StudentClassReal + ". I live in " + Address + ". My Advanced Windows Study Username is " + Username + ", and my password is " + Password, "Information Verification", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If StudentInformationVerification = DialogResult.Yes Then
Dim SQLStatement As String = "INSERT INTO people(FirstName, SecondName, Class, Address, Username, Password) VALUES('" & FirstName & "','" & SecondName & "', '" & StudentClassReal & "', '" & Address & "', '" & Username & "', '" & Password & "')"
SaveName(SQLStatement)
My.Computer.Registry.LocalMachine.SetValue("Study", "1")
SuccessfulMessage = 1
Me.Close()
End If
If StudentInformationVerification = DialogResult.No Then
End If
Else
'Nothing
End If
End Sub
'MYSQL Connection
Private Sub WindowsAdvancedStudyStartingForms_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim RegistryCheck As String = My.Computer.Registry.LocalMachine.GetValue("Study")
If RegistryCheck = 1 Then
LoginForm1.Show()
Me.Close()
End If
APasswordTextBox.UseSystemPasswordChar = True
SQLConnection:
SQLConnection.ConnectionString = ServerString
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
If SuccessfulMessage = 0 Then
MessageBox.Show("Connected to Windows Advanced Study Database", "Connection to Database Passed", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
Else
SQLConnection.Close()
MessageBox.Show("Could not Connect to Windows Advanced Study Database", "Connection to Database Failed", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error)
If DialogResult.Retry Then
GoTo SqlConnection
End If
If DialogResult.Cancel Then
Close()
End If
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Public Sub SaveName(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
MessageBox.Show("Welcome to Advanced Windows Studying", "Authentication Successful", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
End Class
Use parameters. Turn on Option Strict.
You won't need all those Dim's for the student info.
You can pass your connection string to the constructor of the MySQLConnection.
Move your validation code to the Validat event of the various controls. Look up how to cancel the event so focus stays on the appropriate control.
You can pass your SQL string and the connection directly to the connection constructor.
Using...EndUsing statements will ensure that objects are closed and disposed properly even if there is an error. This is very important to ensure that connections are closed.
Don't use GoTo. This is only in the language for backward compatibility and should not be used in new code. (leads to spaghetti code)
In a real application, passwords would never be stored as plain text but that is a topic for another day.
In your SQL statements you need to surround and MySQL reserved words with back ticks (`) This is the character below the tilde (~) and is the quoted identifier for MySQL. Actually, it doesn't hurt to surrond all table names and column names with the back tick to be safe.
I cannot test this code because I don't have your database.
Imports MySql.Data.MySqlClient
Public Class MySQLStudent
Dim strConnection As String = "Server=myServer;User ID=myID;Passwordmy=Password;Database=myDatabase;SSLMode=None"
Private Sub RegisterStudent()
Using cn As New MySqlConnection(strConnection)
Dim SQLStatement As String = "Select Count(*) From people where Username = #UserName;"
Using cmdV As New MySqlCommand(SQLStatement, cn)
cn.Open()
Dim rowCount As Integer = CInt(cmdV.ExecuteScalar())
cn.Close()
If rowCount > 0 Then
MessageBox.Show("Sorry that username is in use; please enter another one.")
AUsernameTextBox.Focus
Exit Sub
End If
End Using
SQLStatement = "INSERT INTO people(FirstName, SecondName, `Class`, Address, `Username`, `Password`) VALUES(#FirstName, #SecondName', #StudentClassValue, #Address, #UserName, #Password);"
Using cmd As New MySqlCommand(SQLStatement, cn)
cmd.Parameters.Add("#FirstName", MySqlDbType.String).Value = AFirstNameTextBox.Text
cmd.Parameters.Add("#SecondName", MySqlDbType.String).Value = ASecondNameTextBox.Text
cmd.Parameters.Add("#StudentClassValue", MySqlDbType.String).Value = ASelectClassComboBox.SelectedItem
cmd.Parameters.Add("#Address", MySqlDbType.String).Value = AAddressTextBox.Text
cmd.Parameters.Add("#Username", MySqlDbType.String).Value = AUsernameTextBox.Text
cmd.Parameters.Add("#Password", MySqlDbType.String).Value = APasswordTextBox.Text
cn.Open()
With cmd
.CommandType = CommandType.Text
.ExecuteNonQuery()
End With
End Using
End Using
MessageBox.Show("Welcome to Advanced Windows Studying", "Registration Successful", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
Private Sub LogInStudent()
Using cn As New MySqlConnection(strConnection)
Using cmd As New MySqlCommand("Select Count(*) From people Where `Username` = #UserName And `Password` = #Password;", cn)
cmd.Parameters.Add("#UserName", MySqlDbType.String).Value = AUsernameTextBox.Text
cmd.Parameters.Add("#Password", MySqlDbType.String).Value = APasswordTextBox.Text
cn.Open()
Dim rowCount As Integer = CInt(cmd.ExecuteScalar)
cn.Close()
If rowCount <> 1 Then
MessageBox.Show("Sorry, invalid login.")
Exit Sub
End If
MessageBox.Show("Successful login.")
'Show the next form of the application
End Using
End Using
End Sub
End Class

VB.net not working with SQL

I have a problem that is eating my brains out.
I have a project with 2 forms : 1 that extracts the data from my database ( name and surname) and another one that checks out if the user input of the user is correct (matching name and surname) . The code for the 1'st form is :
http://pastebin.com/rg5GMuu6
The code for the second is pasted here
I have no idea whatsoever how to repair this error. I've heard something about some sort of an adapter or something......Help
Ty in advance
I am using MySQL (Easy PHP);
Uploading some pics:
The first form is working without any problems, the second one gives me this error
Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class Form2
Dim dbCon As MySqlConnection
Dim strQuery As String = ""
Dim SQLCmd As MySqlCommand
Dim DR As MySqlDataReader
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
'just a message
MsgBox(" You are searching for the users: " & vbCrLf & "Name: " & TextBox1.Text & vbCrLf & "Surname: " & TextBox2.Text)
' connecting to the database
dbCon = New MySqlConnection("Server = localhost; Database = users; Uid = root; Pwd = password")
strQuery = "SELECT users.name, users.surname FROM users" & _
" WHERE users.name = #Username AND users.surname = #UserPassword"
SQLCmd = New MySqlCommand(strQuery, dbCon)
SQLCmd.Parameters.AddWithValue("#Username ", TextBox1.Text)
SQLCmd.Parameters.AddWithValue("#UserPassword", TextBox2.Text)
'Database open
dbCon.Open()
DR = SQLCmd.ExecuteReader
If DR.HasRows = 0 Then
MsgBox("Not a match", MsgBoxStyle.Critical)
Else
MsgBox("You guessed the correct name: " & TextBox1.Text & "and the surname: " & TextBox2.Text)
End If
'Close
DR.Close()
dbCon.Close()
Catch ex As Exception
MsgBox("Failure to communicate " & vbCrLf & vbCrLf & ex.Message)
End Try
End Sub
End Class
Captured all the errors with the debugger
There seems to be odd situations with the .AddWithValue statement. I have found it better to set parameter values with the following two lines of code.
cmd.Parameters.Add(New SqlParameter("#UserName", Data.SqlDbType.NVarChar)).Direction = ParameterDirection.Input
cmd.Parameters("#UserName").Value = textbox1.text'obviously don't need this if it is an Output Param

Automatic verify the Fingeprint of a user [BLOB]

Hi? I have here fingerprint scanner. I want to automatically verified user's fingerprint when they are touching the scanner but I cant.
I have here codes but before you verify the fingerprint if it correct, you need to put first his/her userID.
This is my codes:
Private Sub SaveButton_Click() Handles SaveButton.Click
Using files As New IO.MemoryStream
Template.Serialize(files)
objconn.Open()
If Not Template Is Nothing Then
Dim cmd = New MySqlCommand("INSERT INTO employeefp " +
"SET id=#id, " +
"FP=#FP " +
" ", objconn)
cmd.Parameters.Add(New MySqlParameter("#id", TextBox1.Text))
cmd.Parameters.Add(New MySqlParameter("#FP", Template.Bytes))
cmd.ExecuteNonQuery()
objconn.Close()
MessageBox.Show("Template Successfuly Saved.", "Finger Enrolled")
End If
End Using
End Sub
And this my verify button codes:
Private Sub VerifyButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles VerifyButton.Click
If TextBox1.Text = "" Then
MsgBox("Please input id no.", MsgBoxStyle.Information)
Else
objconn.Open()
Dim cmd As New MySqlCommand("SELECT * FROM employeefp where id ='" & TextBox1.Text & "'", objconn)
Dim rdr As MySqlDataReader = cmd.ExecuteReader()
rdr.Read()
If rdr.HasRows Then
Dim Verifier As New VerificationForm
Verifier.Verify(Template)
Else
MsgBox("The id doesn`t exist", MsgBoxStyle.Information)
End If
End If
objconn.Close()
End Sub
i thought its all about in templates.bytes but i don't know what will I do.
Thanks in advance. Hope you will help me.

Limiting the time in and time out in a day in VB.NET?

I have developed a time monitoring system using fingerprint where the employee will scan his/her finger then it will record the time in and time out. But my problem is logging in and logging out by the employee is unlimited. Is there a solution where the employee can log in and log out ONCE IN A DAY? Every employee will log in and log out once. Here is my code for my Daily Time Record Form: (Im using visual studio 2010/Digital Persona UareU for my scanner)
Imports MySql.Data.MySqlClient
Imports System.Windows.Forms
Imports DPFP
Public Class frmDTR
Dim counter As Integer = 0
Dim oConn As New MySqlConnection(ConnectionString.ConnString)
Private matcher As DPFP.Verification.Verification
Private matchResult As DPFP.Verification.Verification.Result
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
Me.Close()
End Sub
Public Sub SEARCH_EMPLOYEE()
Try
'Load From DB
GlobalFunctions.db_connect()
Dim reader As MySqlDataReader
Dim command As MySqlCommand = connection.CreateCommand()
command.CommandText = "SELECT * FROM employee_records WHERE ID_Number='" & strid & "'" 'check tag number if existing
reader = command.ExecuteReader()
If (reader.HasRows) Then
While (reader.Read())
With Me
'plot the data into controls
.txtID.Text = reader(1).ToString
.txtFirst.Text = reader(2).ToString
.txtMiddle.Text = reader(3).ToString
.txtLast.Text = reader(4).ToString
.txtAge.Text = reader(5).ToString
.txtBday.Text = reader(6).ToString
.txtDepartment.Text = reader(7).ToString
.txtYear.Text = reader(8).ToString
.txtGender.Text = reader(9).ToString
.txtContact.Text = reader(10).ToString
.txtMobile.Text = reader(11).ToString
.txtEmail.Text = reader(12).ToString
'fetch image from database
Dim imgBytes() As Byte = reader("image") 'image field
Dim image As Bitmap = New Bitmap(New System.IO.MemoryStream(imgBytes)) 'convert binary to image
.ProfilePic.Image = image 'show picture to picture box
End With
Call LOG_EMP() 'look up if login /log out
Timer1.Enabled = True
End While
Else
'Me.lblStatus.Text = "ID not recognized!"
End If
Catch ex As Exception
MessageBox.Show("Error scanning: " & ex.Message)
End Try
GlobalFunctions.connection.Close()
End Sub
Public Sub LOG_EMP()
Try
' Load From DB
GlobalFunctions.db_connect()
Dim reader As MySqlDataReader
Dim command As MySqlCommand = connection.CreateCommand()
command.CommandText = "SELECT * FROM employee_logs WHERE ID_Number='" & strid & "' AND Time_Out='Null'"
reader = command.ExecuteReader()
If (reader.HasRows) Then
While (reader.Read())
End While
'logout
Call EMP_LOGOUT()
Else
'log in
Call EMPT_LOGIN()
End If
Catch ex As Exception
MessageBox.Show("Error scanning: " & ex.Message)
End Try
GlobalFunctions.connection.Close()
End Sub
'insert login data
Public Sub EMPT_LOGIN()
' Connect to Database
GlobalFunctions.db_connect()
Dim command As MySqlCommand
Dim transaction As MySqlTransaction
transaction = GlobalFunctions.connection.BeginTransaction()
Try
command = New MySqlCommand("INSERT INTO employee_logs values('','" & txtID.Text & "','" & txtFirst.Text & "','" & txtMiddle.Text & "','" & txtLast.Text & "','" & txtDepartment.Text & "','" & Date.Today & "','" & TimeOfDay & "','Null') ", GlobalFunctions.connection, transaction)
command.ExecuteNonQuery()
transaction.Commit()
'sms = txtFirst.Text & " Enter the Building Premises #" & Now 'actual sms
lblStatus.ForeColor = Color.Lime
Dim SAPI
SAPI = CreateObject("SAPI.spvoice")
SAPI.Speak("Welcome!" & txtFirst.Text)
Me.lblStatus.Text = "Successfully Logged IN! Welcome!" 'set status to login
'Will_SendSMS() 'send sms to number
Catch ex As MySqlException
MessageBox.Show("Error in inserting new record! Error: " & ex.Message, "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
transaction.Rollback()
End Try
'close connections
GlobalFunctions.connection.Close()
End Sub
Public Sub EMP_LOGOUT()
' Connect to Database
GlobalFunctions.db_connect()
' Dim command As MySqlCommand
Dim transaction As MySqlTransaction
transaction = GlobalFunctions.connection.BeginTransaction()
Try
GlobalFunctions.execute_nonquery("Update employee_logs set Time_Out='" & TimeOfDay & "' WHERE ID_Number='" & strid & "' AND Time_Out='Null' AND Date='" & Date.Today & "'")
transaction.Commit()
'sms = txtFirst.Text & " Left the Building Premises #" & Now & "Powered by: " ' actual sms to be sent
lblStatus.ForeColor = Color.Lime
Dim SAPI
SAPI = CreateObject("SAPI.spvoice")
SAPI.Speak("Goodbye!" & txtFirst.Text)
lblStatus.Text = "Successfully Logged OUT! Goodbye!" ' set status to logout
'Will_SendSMS() 'send sms
Catch ex As MySqlException
MessageBox.Show("Error in updating a record! Error: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error)
transaction.Rollback()
End Try
' close connections
GlobalFunctions.connection.Close()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
'counter for display
counter += 1
If counter = 6 Then
Call ClearTextBox(Me)
lblStatus.ForeColor = Color.Lime
Me.lblStatus.Text = "Please scan your finger....."
Lblverify.ForeColor = Color.Black
Lblverify.Text = "Status"
ProfilePic.Image = Nothing
Timer1.Enabled = False
counter = 0
End If
End Sub
Private Sub frmDTR_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
Try
Me.VerificationControl.Focus()
Catch ex As MySqlException
MessageBox.Show("System Error: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub frmDTR_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
matcher = New Verification.Verification()
matchResult = New Verification.Verification.Result
Me.VerificationControl.Focus()
Dim SAPI
SAPI = CreateObject("SAPI.spvoice")
SAPI.Speak("Please scan your finger")
End Sub
Private Sub VerificationControl_OnComplete(ByVal Control As Object, ByVal FeatureSet As DPFP.FeatureSet, ByRef EventHandlerStatus As DPFP.Gui.EventHandlerStatus) Handles VerificationControl.OnComplete
Dim strSQL As String = "Select * from finger_template"
Dim oDa As New MySqlDataAdapter(strSQL, oConn)
Dim dt As New DataTable
Dim dr As DataRow
Try
oDa.Fill(dt)
For Each dr In dt.Rows
Lblverify.ForeColor = Color.Red
Lblverify.Visible = True
Dim bytes As Byte() = Nothing
bytes = dr.Item("byte_template")
Dim tmplate = New DPFP.Template()
tmplate.DeSerialize(bytes)
matcher.Verify(FeatureSet, tmplate, matchResult)
If matchResult.Verified Then
EventHandlerStatus = DPFP.Gui.EventHandlerStatus.Success
strid = dr.Item("Account_ID")
Call SEARCH_EMPLOYEE()
Exit For ' success
End If
If Not matchResult.Verified Then EventHandlerStatus = DPFP.Gui.EventHandlerStatus.Failure
Lblverify.Text = "Status"
lblStatus.Text = "Unrecognize fingerprint....."
Lblverify.ForeColor = Color.Red
lblStatus.ForeColor = Color.Red
Timer1.Start()
Next
Catch ex As Exception
End Try
End Sub
End Class
This is very nice that you are developing this logic. Actually I have come a crossed YOUR question. Now I can recommend you some vb.net code using back end MS ACCESS 2007 .well You just validate when an employee logged in then put this code after log In button or what ever you are using .
Dim cmd1 as oledbcommond
cmd1 = New OleDbCommand("SELECT * FROM LOGTIME WHERE timein<>null and timeout<>null and dt='" & Label8.Text & "' and eid='" & txtemid.Text & "' ", cn)
dr = cmd1.ExecuteReader()
If dr.Read Then
MessageBox.Show("Already this Employee ID contains today's attendance,now you can't Log again", "Information On Your ID", MessageBoxButtons.OK, MessageBoxIcon.Information)
cmd1.Dispose()
cn.Close()
Exit Sub
End If
just follow the steps
Use normal login button which will validate for user
then if the authenticate user then show his login time in another textbox in the same form.and
use one more textbox to show the logout time ,now
1)use two buttons a)button1 as logintime button and b)button2 as logout time button
2)Then write code to add the login time into the data base,and for ur better understanding put one message box too which will shows the"Time in added to the database" and after that put the above code which will validate the current day attendance if the employee wants to login twice or thrice in a day this code will not allow him to login again only once he/she can ... and code the above behind the login button
note:-keep in mind that all the procedure will work after the employee log out ..Hope this will help you out..

MysqlException was unhandled DataReader with this connection must be closed vb.net

I have encountered this problem:
ERROR: There is already an open DataReader associated with this Connection which must be closed first.
Please have a look on my code:
Dim sqlQuery As String = "SELECT * FROM users"
Dim myAdapter As New MySqlDataAdapter
If txtUsername.Text = String.Empty And txtPassword.Text = String.Empty Then
MsgBox("Enter username and password", MsgBoxStyle.Exclamation, "Tea Sparkle POS")
Else
Dim sqlquerry = "Select * From users where username = '" + txtUsername.Text + "' And password= '" + txtPassword.Text + "'"
Dim myCommand As New MySqlCommand()
myCommand.Connection = SQLConnection
myCommand.CommandText = sqlquerry
'Starting The Query
myAdapter.SelectCommand = myCommand
Dim mydata As MySqlDataReader
mydata = myCommand.ExecuteReader()
'To check the Username and password and to validate the login a
If mydata.HasRows = 0 Then
MsgBox("Invalid Login")
txtPassword.Clear()
txtUsername.Clear()
Else
Dim authorityid = 0
While mydata.Read()
authorityid = mydata.GetInt32("authorityid")
End While
MsgBox("Welcome " + txtUsername.Text + "!")
If authorityid = 1 Then
MainForm.Show()
Else
MainForm.Show()
End If
Me.Hide()
End If
End If
Private Sub Login_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
SQLConnection.ConnectionString = ServerString
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
Else
SQLConnection.Close()
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
This error is in this line:
mydata = myCommand.ExecuteReader()
What's wrong with this? Any help is truly appreciated.
What's wrong with this?
Well, it looks like you're reusing an existing connection:
myCommand.Connection = SQLConnection
Don't do that. Create a new connection each time you need to talk to the database, and close it when you've finished, using a Using statement to make sure it gets closed even if an exception is thrown.
Additionally, use a Using statement for your command, and another for your reader - these are all resources you should be closing.
Oh, and it also looks like you're doing this in the UI thread, which is a bad idea as your UI will be unresponsive while the database access is ongoing.