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

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.

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

Connection must be valid and open VB.Net

I want to connect my MySQL to my VB.net.
I am only using Login Form.
I have given the code but the code gives me this error message: Connection must be valid and open
This is my code:
Imports MySql.Data.MySqlClient
Public Class Login
Dim MysqlConn As MySqlConnection
Dim Command As MySqlCommand
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString ="server=db4free.net;port=3306;userid=exd****;password=****;database=exd****"
Dim Reader As MySqlDataReader
Try
MysqlConn.Open()
Dim Query As String
Query = "select * from member where Username='" & UsernameTxt.Text & "' and Password='" & PasswordTxt.Text & "' "
Command = New MySqlCommand
Reader = Command.ExecuteReader
Dim count As Integer
count = 0
While Reader.Read
count = count + 1
End While
If count = 1 Then
MessageBox.Show("Correct !")
ElseIf count > 1 Then
MessageBox.Show("Duplicate !")
Else
MessageBox.Show("Not Correct !")
End If
MysqlConn.Close()
Catch ex As Exception
MsgBox(ex.Message)
Finally
MysqlConn.Dispose()
End Try
End Sub
End Class
Can anyone help me to fix that? Thanks.
To associate your Query and Command with the connection you need to do this:
Command = New MySqlCommand(Query, MysqlConn)
You can then perform operations to retrieve the data you need.
At no point do you associate your MysqlConn nor Query to your Command before trying to call ExecuteReader on it. As such, it doesn't have a valid connection at that time.
Query = "select * from member where Username='" & UsernameTxt.Text & "' and Password='" & PasswordTxt.Text & "' ", nombredelaconexion

how to display selected value in mysql database in label through vb.net

i have a code but it's not working. i was trying to put a value in label2 but it's not working. please help me.
Private Sub student_no_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles student_no.Click
MySqlConnection = New MySqlConnection
MySqlConnection.ConnectionString = "server = localhost; port=3307; user id = root; password = 1234; database = sample;"
Dim READER As MySqlDataReader
Try
MySqlConnection.Open()
Dim query As String
query = " select id from sample.student where last_name = '" & txtlastname.Text & "' "
Dim Command As New MySqlCommand(query, MySqlConnection)
READER = Command.ExecuteReader
Label2.Text = query.ToString
MessageBox.Show("Student Number Generated")
MySqlConnection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MySqlConnection.Dispose()
End Try
End Sub
You are using .ToString on query, which is a string. What you should be doing is operations on the READER object.
Since SELECT will always return a list of results, you have to treat the results as such, like...
While READER.Read()
MessageBox.Show((READER.GetInt32(0)))
End While
.Read() returns the next element in the returned rowset
If READER.Read() Then
Label2.Text = READER.GetString(0)
End If

Inserting VB.net Label to mysql table

How to Inserting Label.text data into mySql table.
i have no problem with textbox.text but i can't figure out how it with Label.text
i try the same code with textbox.text
parameterB_Answer.Value = TextBox1.Text
it work find but when i try with
parameterB_Answer.Value = Label1.Text
mySqlReader seems can't read it.
Update:
1.1.1 is label1.text. My Idea is to insert the text "1.1.1" from Label1 as Primary key and the Textbox(textbox1.text) as the following
my code is:
Try
Dim StrSQL As String = "INSERT INTO boranga" & _
"(IdBorangA,Answers)" & _
"VALUES (#B_IdA,#B_Answer);"
Dim myCommand As MySqlCommand = New MySqlCommand(StrSQL, conn.open)
myCommand.CommandType = CommandType.Text
Dim parameterB_IdA As MySqlParameter = New MySqlParameter("#B_IdA", MySqlDbType.VarChar, 300)
parameterB_IdA.Value = Label1.Text
Dim parameterB_Answer As MySqlParameter = New MySqlParameter("#B_Answer", MySqlDbType.VarChar, 300)
parameterB_Answer.Value = TextBox1.Text
With myCommand.Parameters
.Add(parameterB_IdA)
.Add(parameterB_Answer)
End With
Dim result As MySqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
MsgBox("Tersimpan", vbYes, "boranga")
Catch SqlEx As MySqlException
Throw New Exception(SqlEx.Message.ToString())
End Try
but when I change the value of Label1.text (1.1.1) to 111, it works just fine. probably because I put INT for the column for label1.text to fill while "1.1.1" isn't integer
thank a lot
PS:seems i can't post image because low of reputation
Try using this code format first of all:
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
Dim conn As MySqlConnection
'Connect to the database using these credentials
conn = New MySqlConnection
conn.ConnectionString = "server=your server site (generally long url); user id=login id for mysql user; password=self explanatory; database=name of the DB you're trying to reach"
'Try and connect (conn.open)
Try
conn.Open()
Catch myerror As MySqlException 'If it fails do this... (i.e. no internet connection, etc.)
MsgBox("Error connecting to database. Check your internet connection.", MsgBoxStyle.Critical)
End Try
'MySQL query (where to call for information)
Dim myAdapter As New MySqlDataAdapter
'Tell where to find the file with the emails/passes stored
Dim sqlquery = "SELECT * FROM the database you selected above WHERE Email = '" & txtEmail.Text & "' AND Password = '" & txtPassword.Text & "'"
Dim myCommand As New MySqlCommand
myCommand.Connection = conn
myCommand.CommandText = sqlquery
'Start query
myAdapter.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader
If myData.HasRows = 0 Then
MsgBox("Invalid email address or password.", MsgBoxStyle.Critical)
Else
MsgBox("Logged in as " & txtEmail.Text & ".", MsgBoxStyle.Information)
Me.Close()
End If
End Sub
And to insert label.text try replacing one of the textbox.text fields first and see if it will accept it. If it does, then the answer was all in the formatting.
Also, do not forget to call:
imports mysql.data.mysqlclient
and make sure to add the mysql.data reference.

button not working when i insert new data

when I input data are not yet available. button does not work
but when I enter existing data in the database, the button work for find existing records in the database and msgbox.appear
this my coding. (i am using Microsoft Visual Basic 2008 express edition database mysql)
Imports MySql.Data.MySqlClient
Public Class Form2
Public conn As MySqlConnection
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Application.DoEvents()
Button1.Focus()
conn = New MySqlConnection
'conn.ConnectionString = "server=localhost;database=ilmu;userid=root;password= ''"
Try
conn.Open()
Catch ex As Exception
MessageBox.Show("Error1: " & ex.Message)
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
conn = New MySqlConnection("server=localhost;database=ilmu;userid=root;password= ''")
Try
conn.Open()
Dim sqlquery As String = "SELECT * FROM visitor WHERE nama = '" & TextBox1.Text & "';"
Dim data As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = sqlquery
command.Connection = conn
adapter.SelectCommand = command
data = command.ExecuteReader
While data.Read()
If data.HasRows() = True Then
If data(2).ToString = TextBox2.Text Then
command = New MySqlCommand
command.Connection = conn
tkhupd = Now.ToString("yyyy-MM-dd HH:mm:tt")
command.CommandText = "INSERT INTO visitor(noK,khupd)VALUES ('" & TextBox1.Text & "','" & tkhupd & "')"
command.ExecuteNonQuery()
MessageBox.Show(" Berjaya, Sila Masuk. ", "Tahniah", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MsgBox("exist")
End If
Else
MsgBox("Failed Login.")
End If
End While
Catch ex As Exception
End Try
End Sub
End Class
I am not sure what you are trying to do when there is not matching record in the database, but you don't have any code that would be hit in the case of no matching entries.
If there are no matching records, your while condition isn't met and nothing in the loop happens.
Fixing it likely involves rearranging the order of your loop and your if condition.
Check to see if data.hasRows first.
Example:
If data.HasRows() = True Then
While Data.Read
//code here for found rows
End While
Else
//code for no matching entries
End If
And as has been mentioned in Joel's comment, you really should look at using parameterized queries.
example of your insert command altered:
command.CommandText = "INSERT INTO visitor(noK,khupd)VALUES (?noK,?khupd)"
command.Parameters.AddWithValue("?noK",TextBox1.Text)
command.Parameters.AddWithValue("?khupd", tkhupd)
command.ExecuteNonQuery()