Invalid Operation Exception was unhandled - can't update 2 things at once - mysql

This form I made allows the user to change their username, password and/or security passphrase, and it connects and updates on XAMPP database. I have tried looking online, but I am very new to VB and nothing really makes sense.
The problem is I can change any one of them, but if I try change the other after I changed one I get the error:
InvalidOperationException was unhandled
Connection must be valid and open
The error comes here: reader = objcommand.ExecuteReader
This is my code:
`Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class frmAccountSettings
Private Sub frmAccountSettings_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
objconnection.Open()
objdataadapter.SelectCommand = New MySqlCommand
objdataadapter.SelectCommand.Connection = objconnection
objdataadapter.SelectCommand.CommandText = "Select * FROM Login"
End Sub
Private Sub btnBack_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBack.Click
frmMainMenu.Show()
Me.Hide()
End Sub
Private Sub btnChangeUsername_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnChangeUsername.Click
Dim password1, newusername As String
password1 = InputBox("What is the current password?")
sqlstring = "SELECT password FROM Login WHERE Password = '" &
password1 & "'"
objcommand = New MySqlCommand(sqlstring, objconnection)
reader = objcommand.ExecuteReader
If reader.Read Then
reader.Close()
newusername = InputBox("Enter a new username")
sqlstring = "UPDATE `Login` SET `username` = '" & newusername &
"' WHERE `Login`.`password` = '" & password1 & "'"
objdataadapter.SelectCommand.CommandText = sqlstring
objdataadapter.SelectCommand.CommandType = CommandType.Text
objdataset = New DataSet
objdataadapter.Fill(objdataset, "Login")
objconnection.Close()
Else
MsgBox("Incorrect Username. Please make sure your credentials are correct and try again.", MsgBoxStyle.Critical, "Authentication Failed")
reader.Close()
End If
End Sub
Private Sub btnChangePassword_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnChangePassword.Click
Dim oldpassword, newpassword1 As String
oldpassword = InputBox("What is the current password?")
sqlstring = "SELECT password FROM Login WHERE Password = '" &
oldpassword & "'"
objcommand = New MySqlCommand(sqlstring, objconnection)
reader = objcommand.ExecuteReader
If reader.Read Then
reader.Close()
newpassword1 = InputBox("Enter a new password")
sqlstring = "UPDATE `Login` SET `password` = '" & newpassword1 &
"' WHERE `Login`.`password` = '" & oldpassword & "'"
objdataadapter.SelectCommand.CommandText = sqlstring
objdataadapter.SelectCommand.CommandType = CommandType.Text
objdataset = New DataSet
objdataadapter.Fill(objdataset, "Login")
objconnection.Close()
Else
MsgBox("Incorrect Password. Please make sure your credentials are correct and try again.", MsgBoxStyle.Critical, "Authentication Failed")
reader.Close()
End If
End Sub
Private Sub btnChangeSecurity_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnChangeSecurity.Click
Dim password2, newsecurity As String
password2 = InputBox("What is the current password?")
sqlstring = "SELECT password FROM Login WHERE Password = '" &
password2 & "'"
objcommand = New MySqlCommand(sqlstring, objconnection)
reader = objcommand.ExecuteReader
If reader.Read Then
reader.Close()
newsecurity = InputBox("Enter a new security passphrase")
sqlstring = "UPDATE `Login` SET `security` = '" & newsecurity &
"' WHERE `Login`.`password` = '" & password2 & "'"
objdataadapter.SelectCommand.CommandText = sqlstring
objdataadapter.SelectCommand.CommandType = CommandType.Text
objdataset = New DataSet
objdataadapter.Fill(objdataset, "Login")
objconnection.Close()
Else
MsgBox("Incorrect Password. Please make sure your credentials are correct and try again.", MsgBoxStyle.Critical, "Authentication Failed")
reader.Close()
End If
End Sub
End Class
`

I think that there are a couple of errors in your code. The most serious one is a logic flaw.
You can't be sure that two users choose always different passwords. You need to make sure that your datatable Login has a primary key on the username field and use that field in your queries to uniquely identify the records to be changed. Also, changing a username used as primary key is not an easy task. You need to check if the new user name is not already taken by another user. And if your application is used in a shared environment you need to account also for concurrent changes (two user that decide to change their username to the same new name)
Also, the SelectCommand of the adapter is not the appropriate method to execute database updates. But, there is no need at all to involve the adapter for these operations, you could do everything with a MySqlCommand.
There is another security problem with storing passwords in clear text in a datatable. You should never do that, instead you should apply a hashing function to your password before storing it in the table.
However, limiting my answer to the current problem and excluding the concurrency issue, I would change your code in this way (of course username should be the primary key) ....
Dim password1, newusername, oldusername As String
oldusername = InputBox("Type the current username")
password1 = InputBox("What is the current password?")
newusername = InputBox("Enter a new username")
' identify the current user ... '
sqlstring = "SELECT COUNT(*) FROM `Login` WHERE `username` = #uname AND `password` = #pwd"
objcommand = New MySqlCommand(sqlstring, objconnection)
objcommand.Parameters.AddWithValue("#uname", oldusername)
objcommand.Parameters.AddWithValue("#pwd", password1)
Dim result = objcommand.ExecuteScalar
if result IsNot Nothing AndAlso Convert.ToInt32(result) > 0 Then
' we have good credentials, but the new user name should be unique '
sqlstring = "SELECT COUNT(*) FROM `Login` WHERE `username` = #uname"
objcommand = New MySqlCommand(sqlstring, objconnection)
objcommand.Parameters.AddWithValue("#uname", newusername)
Dim result = objcommand.ExecuteScalar
if result Is Nothing OrElse Convert.ToInt32(result) = 0 Then
' we could change the username of the current user '
sqlstring = "UPDATE `Login` SET `username` = #newame WHERE `username` = #oldname"
objcommand = New MySqlCommand(sqlstring, objconnection)
objcommand.Parameters.AddWithValue("#newame", newusername)
objcommand.Parameters.AddWithValue("#oldname", oldusername)
objcommand.ExecuteNonQuery()
else
MessageBox.Show("Username already taken, choose a different one")
End If
Else
MessageBox.Show("Invalid credentials given")
End If
In this way you use the combination of user and password to uniquely identify your user in the database and change the exact record involved.
In the same way you ask for the username and password when you want to change the password field and update the field only if the username and password match.
EDIT According to your comment above, if there is only one user in the database then you could execute directly the change without any complex checking. (But this is really a case that could not be assumed to be generally common)
sqlstring = "UPDATE `Login` SET `username` = #newame WHERE `password` = #pwd"
objcommand = New MySqlCommand(sqlstring, objconnection)
objcommand.Parameters.AddWithValue("#newame", newusername)
objcommand.Parameters.AddWithValue("#pwd", password1)
objcommand.ExecuteNonQuery()
Another problem is the connection object. It is a global object opened at the Form_Load event and then is kept hanging around your code but in some places you close it and when you try to execute another database operation you forget to reopen in. It is a good practice to NOT have a global object for the connection, instead build one when required, use it and then destroy it
For example
Private Sub btnChangeSecurity_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnChangeSecurity.Click
Using objconnection = new MySqlConnection(....connectionstring goes here ....)
objconnection.Open()
Dim sqlstring = "UPDATE `Login` SET `username` = #newame WHERE `password` = #pwd"
objcommand = New MySqlCommand(sqlstring, objconnection)
objcommand.Parameters.AddWithValue("#newame", newusername)
objcommand.Parameters.AddWithValue("#pwd", password1)
objcommand.ExecuteNonQuery()
End Using
End Sub
If you put your database access code inside a using statement like above, you create the connection object, open it, use it and when done, the End Using statement will close and destroy the connection.

Related

Verifying StudentId and StudentPassword with mySql Database using Visual Basic

I am working on a school voting system. I Have tried this several times and there is no error but my login button doesn't work if I enter details and click login.
I use Visual Studio 2013 and would be glad if anyone can be of assistance.
Thank you
Imports MySql.Data.MySqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ConnectToSQL()
End Sub
'connecting to sql method
Private Sub ConnectToSQL()
Dim con As New MySqlConnection
Dim cmd As New MySqlCommand
Dim StudentId As String
Dim StudentPassword As String
Try
If con.ConnectionString = "Data source= localhost; port=3306; database= Students; user=root; password=;" Then
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT StudentId, StudentPassword, StudentName FROM members"
Dim lrd As MySqlDataReader = cmd.ExecuteReader()
If lrd.HasRows Then
While lrd.Read()
StudentId = lrd("StudentId").ToString
StudentPassword = lrd("StudentPassword").ToString
If StudentPassword = TextBox1.Text And StudentId = TextBox1.Text Then
MsgBox("you logged in succesfully")
Me.Hide()
Form2.Show()
TextBox1.Text = ""
TextBox2.Text = ""
End If
End While
Else
MsgBox("Username and password do not match")
TextBox2.Text = ""
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
TextBox1.Text = ""
TextBox2.Text = ""
TextBox1.Focus()
End Sub
End Class
From what I can see your problem is your first if statement:
If con.ConnectionString = "Data source= localhost; port=3306; database= Students; user=root; password=;" Then
This checks if the connectionstring is set to this value and will most definitely evaluate to false.
I assume that you want to set these settings and then open the connection to the database and not check if these settings are the set to a specific string
To make it work just remove this if statement and just set the connectionstring like this and then open the connection
con.ConnectionString = "Data source= localhost; port=3306; database= Students; user=root; password=;" Then
First, I'm going to assume you have a typo here, as it's using the username and password as the same textbox:
If StudentPassword = TextBox1.Text And StudentId = TextBox1.Text Then
Password is probably the 2nd one, forming this:
If StudentPassword = TextBox2.Text And StudentId = TextBox1.Text Then
Since you are a student and new to this, not going to get into the parameters discussion, or SQL parameters or filtering, hashing passwords or anything like that, but a couple changes:
Your else on the not hasrows:
MsgBox("Username and password do not match")
TextBox2.Text = ""
The problem with this is that in your case, having no rows just means there's no members in the database, not really information you need, or should tell someone.
Also, you don't need to blank out the username and password if you are going to hide the form anyway. The studentFound var below is used to identify if a match was found. We want to display an error if no match was found.
So, that gives us this:
While lrd.Read()
StudentId = lrd("StudentId").ToString
StudentPassword = lrd("StudentPassword").ToString
If StudentPassword = TextBox2.Text And StudentId = TextBox1.Text Then
MsgBox("you logged in succesfully")
Me.Hide()
Form2.Show()
studentFound = True
End If
End While
If Not studentFound Then
MsgBox("Username/Password Combination Not Found")
TextBox1.Text = ""
TextBox2.Text = ""
End If

VB.net Login with MySQL

I do not know what went wrong. Im new to vb. Can someone help me? Maybe correct my codes cause I've been spending so much time with this login form of mine. Thanks! here's my code.
By the way, I have a table with 3 columns. Username, Password and Privilege. Whenever I input my Login credentials, it only display the Msgbox Try again.
Imports MySql.Data.MySqlClient
Public Class LoginForm
Dim cn As New MySqlConnection
Dim cmd As MySqlCommand
Dim reader As MySqlDataAdapter
Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click
Dim tblUser As New DataTable
Try
If PasswordTextBox.Text = "" Or UsernameTextBox.Text = "" Then
MessageBox.Show("Please provide your login credentials!")
Else
Dim sql As String
sql = "SELECT * from user_account where username = '" & UsernameTextBox.Text & "' and password = '" & PasswordTextBox.Text & "'"
Using con As New MySqlConnection(My.Settings.ConnectionString)
With cmd
.Connection = con
.CommandText = sql
End With
reader.SelectCommand = cmd
reader.Fill(tblUser)
If tblUser.Rows.Count > 0 Then
Dim userType As String
userType = tblUser.Rows(0).Item(2)
If userType = "admin" Then
MsgBox("Welcome, Admin!")
frmAdminMain.Show()
ElseIf userType = "encoder" Then
MsgBox("Welcome, User!")
MainForm.Show()
End If
Else
MsgBox("Invalid Credentials!")
End If
reader.Dispose()
End Using
End If
Catch ex As Exception
MsgBox("Try Again!")
End Try
End Sub
Add the "New" key word to your command declaration
Dim cmd As New MySqlCommand
"With" just set the properties, it does not initialize the object.

InvalidOperationException was unhandled - Easy fix?

Hi could someone please help me, I am a completely new to coding and just following material my teacher has given me.
I am currently making a vb programme connected to xampp-mysql database
I have made the login form where the user/pass is store on the xampp database. I have included some presence checks for the text boxes and now I am trying to implement a feature into my program where the user can change his/her password using their security passphrase.
My XAMPP database is called: ba-solutions
My table is called Login and my fields are Username, Password and Security
I tried looking online, but nothing makes sense or is relevant to me, but this maybe just because I don't understand it as I am new to coding.
I used the sheets from my teacher to write this code for the programme but when I try to run I get the error:
InvalidOperationException was unhandled
An error occurred creating the form. See Exception.InnerException for details. The error is: Format of the initialization string does not conform to specification starting at index 52.
Here is my all my code from my Login form:
Imports MySql.Data
Imports MySql.Data.MySqlClient
Module procedures_and_variables
Public objconnection As New MySqlConnection("Server=localhost;database=ba-solutions;user id=root;password=")
Public objdataadapter As New MySqlDataAdapter
Public objdataset As DataSet
Public objcommandbuilder As New MySqlCommandBuilder
Public objdatatable As New DataTable
Public rowposition As Integer = 0
Public sqlstring As String
Public tablename As String
Public objcommand As MySqlCommand
Public reader As MySqlDataReader
Public database_path As String = "Server=localhost;database=ba-solutions;user id=root;password="
Public path As String
Public backup As New MySqlBackup
'Procedure which checks whether or not the current connection is open and opens it, if it is closed.
Public Sub connection_checker()
If objconnection.State = ConnectionState.Closed Then
Try
objconnection.Open()
Catch ex As MySqlException
MsgBox("Error connecting to database")
End Try
End If
End Sub
'Procedure which executes any SQL query.
Public Sub SQL_executer()
Call connection_checker()
objdataadapter.SelectCommand = New MySqlCommand
objdataadapter.SelectCommand.Connection = objconnection
objdataadapter.SelectCommand.CommandText = sqlstring
objcommandbuilder = New MySqlCommandBuilder(objdataadapter)
objdataadapter.Fill(objdatatable)
objdataadapter.SelectCommand.CommandType = CommandType.Text
End Sub
'Procedure used to load data from the database for the selected table.
Public Sub initial_load()
Call connection_checker()
Call SQL_executer()
objdataset = New DataSet
objdataadapter.Fill(objdataset, tablename)
objconnection.Close()
End Sub
'Procedure used to update data in a table with the changes made to the data in the datagrid.
Public Sub update_data()
Call connection_checker()
Try
objdataadapter.Update(objdataset, tablename)
MsgBox("Changes accepted", MsgBoxStyle.Information, "Update successfull")
Catch ex As Exception
MsgBox("Changes declined", MsgBoxStyle.Critical, "Update unsuccessfull")
End Try
End Sub
'Procedures used to bind the relevant data to the data grid, with the correct header titles.
Public Sub bind_dataset_client_details()
'NEEDS TO BE COMPLETED FOR ALL DATASETS
End Sub
End module
Public Class frmLogin
Dim form_type As Form
Dim user_table As String
Dim objconnection As New MySqlConnection("Server=localhost;database=ba-solutions;user id=root;password;")
Dim sqlstring As String
Private Sub frmLogin_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
objconnection.Open()
objdataadapter.SelectCommand = New MySqlCommand
objdataadapter.SelectCommand.Connection = objconnection
objdataadapter.SelectCommand.CommandText = "Select * FROM Login"
End Sub
Private Sub Login_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Login.Click
Me.Cursor = Cursors.WaitCursor
'Tries to open the server connection and it will give an error if connection fails.
Try
objconnection.Open()
Catch ex As Exception
MsgBox("Error connecting to database", MsgBoxStyle.Critical, "Database Error")
frmXampp.Show()
End Try
'Checks if the username textbox contains a value, if it does not, it creates an error provider.
If Len(txtUsername.Text) < 1 Then
MsgBox("You must enter a username.", MsgBoxStyle.OkOnly, "Login Error")
End If
'Performs same presence check as above on password textbox.
If Len(txtPassword.Text) < 1 Then
MsgBox("You must enter a password.", MsgBoxStyle.OkOnly, "Login Error")
End If
'SQL query
sqlstring = "SELECT * FROM Login Where username = '" + txtUsername.Text + "' AND password = '" + txtPassword.Text + "'"
'Creates command
objcommand = New MySqlCommand(sqlstring, objconnection)
'Executes command
reader = objcommand.ExecuteReader
'See if user exists
If reader.Read Then
MsgBox("Login Accepted!", MsgBoxStyle.Information, "Login Successful")
'Displays the Main Menu form after a successfull login
frmMainMenu.Show()
Me.Visible = False
Else
'And if authentication has failed, the user will be given an option to retry or exit
reader.Close()
Dim prompt As MsgBoxResult
prompt = MessageBox.Show("Invalid Username or Password. Please make sure your credentials are correct and try again or exit.", "Login Error",
MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning)
If prompt = MsgBoxResult.Cancel Then
Me.Close()
End If
End If
Me.Cursor = Cursors.Arrow
End Sub
Private Sub Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel.Click
Me.Close()
End Sub
Private Sub ForgotPassword_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ForgotPassword.Click
Dim security, newpassword As String
security = InputBox("What is the security passphrase?")
sqlstring = "SELECT security FROM Login WHERE security = '" & security & "'"
objcommand = New MySqlCommand(sqlstring, objconnection)
reader = objcommand.ExecuteReader
If reader.Read Then
reader.Close()
newpassword = InputBox("Enter new password")
sqlstring = "UPDATE 'Login' SET 'password' = '" & newpassword &
"' WHERE 'Login' . 'password' = '" & security & "'"
objdataadapter.SelectCommand.CommandText = sqlstring
objdataadapter.SelectCommand.CommandType = CommandType.Text
objdataset = New DataSet
objdataadapter.Fill(objdataset, "Login")
objconnection.Close()
Else
MsgBox("Invalid Security Passphrase or New Password. Please make sure your credentials are correct and try again.", MsgBoxStyle.Critical, "Authentication Failed")
reader.Close()
End If
End Sub
End Class
Please bear in mind I am a complete newbie and I would really appreciate any help. Thank you.
I think you have an invalid connection string
Try this instead:
Server=localhost;Database=ba-solutions;Uid=root;

String from Database set as public string

Ok from the answer from the previous question the reasoning still applies here but this time A different issue. There is a login system (Loginvb.vb) that I got for the launcher I was creating and was wondering 2 things:
Is there a better way to do the Login check with the database (as in
more secure) (the login style will have a web based registration
setting via PHP script)?
Is there a way to take a certain column (labled as access) in the database and put it
as a public string so I can check if it will equal 1 2 or 3 in a
different form labeled as Main.vb
Here is the current login check:
Public Sub login_Click(sender As Object, e As EventArgs) Handles login.Click
If txtuserName.Text = "" Or txtpassWord.Text = "" Then
MsgBox("You cannot progress until you login....(moron =p)")
Else
'Connects To the Database
Dim connect As MySqlConnection
connect = New MySqlConnection()
connect.ConnectionString = "server=127.0.0.1;user id=sc;Password=derp;database=sclaunch" 'not the actual login ;)
Try
connect.Open()
Catch myerror As MySqlException
MsgBox("Error Connecting to Database. Please Try again !")
End Try
'SQL Query To Get The Details
Dim myAdapter As New MySqlDataAdapter
Dim sqlquerry = "Select * From login where username = '" + txtuserName.Text + "' And password= '" + txtpassWord.Text + "'"
Dim myCommand As New MySqlCommand()
'My fail attempt at what I am trying to do :(
Dim sql22 As MySqlConnection
sql22 = New MySqlConnection()
sql22.ConnectionString = "Select * From login where access ="
'End of fail attempt
myCommand.Connection = connect
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
If mydata.HasRows = 0 Then
MsgBox("Invalid Login")
Else
'fail testing xD
Label3.Text = sql22
MsgBox("You are now Loged In!")
End If
End If
End Sub
Still basically learning more and more as I am coding all this got to love trial and error and the moments where you get stuck =/ (Sorry to the admins or whatever for fixing tag issues still new to the site xD)
Assuming that the same table login that contains the credentials contains also the access column that you want to retrieve, then I have changed a lot of your code
Dim sqlquerry = "Select * From login where username = #name AND password=#pwd"
Dim myCommand As New MySqlCommand(sqlquery, connect)
myCommand.Parameters.AddWithValue("#name", txtuserName.Text)
myCommand.Parameters.AddWithValue("#pwd", txtpassWord.Text)
Dim mydata = myCommand.ExecuteReader
If mydata.HasRows = False Then
MsgBox("Invalid Login")
Else
' the same record that contains the credentials contains the access field'
mydata.Read()
Label3.Text = mydata("access").ToString()
MsgBox("You are now Loged In!")
End If
What I have changed:
Removed the string concatenation and added the appropriate parameters
Removed myAdapter and every references to it (not needed, you don't
fill DataTable/DataSet)
Removed sql22 and every references to it. It's a Connection and you
try to use like a Command
Fixed the check on HasRows (Returns a boolean not an integer. Are you
using Option Strict Off?)

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.