error show on There is already an open DataReader associated with this Command which must be closed first - vb.net

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim n As Integer = 0
str = "select Vote from vote where party='Green'"
cmd = New SqlCommand(str, con)
con.Open()
dr = cmd.ExecuteReader()
if dr.HasRows Then
dr.Read()
n = dr("Vote").ToString()
n = n + 1
Label8.Text = n.ToString()
End If
str = "update Vote set vote='" + n.ToString() + "' where party='Green'"
cmd = New SqlCommand(str, con)
cmd.ExecuteNonQuery()
dr.Read()
cmd.Dispose()
con.Close()
End Sub

The message seems to be pretty clear. You have to close the DataReader before trying to use the connection for another operation
MSDN says
While the SqlDataReader is being used, the associated SqlConnection is
busy serving the SqlDataReader, and no other operations can be
performed on the SqlConnection other than closing it. This is the case
until the Close method of the SqlDataReader is called. For example,
you cannot retrieve output parameters until after you call Close.
....
dr.Close()
str = "update Vote set vote='" + n.ToString() + "' where party='Green'"
cmd = New SqlCommand(str, con)
cmd.ExecuteNonQuery()
' ??? dr.Read()
cmd.Dispose()
con.Close()
By the way, your whole code could be simplified using an ExecuteScalar to retrieve the last vote value and dumping the DataReader
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim n As Integer = 0
str = "select Vote from vote where party='Green'"
Using cmd = New SqlCommand(str, con)
con.Open()
Dim n as Integer
Dim result = cmd.ExecuteScalar()
if result IsNot Nothing Then
n = Convert.ToInt32(result) + 1
else
n = 1
End If
Label8.Text = n.ToString()
str = "update Vote set vote='" + n.ToString() + "' where party='Green'"
cmd.CommandText = str
cmd.ExecuteNonQuery()
con.Close()
End Using
End Sub
In this scenario you use a global connection object and this should be avoided. Remember that it is always better to create, open, use and destroy the connection when you need to use it. SqlClient classes could use the Connection Pooling infrastructure that could help a lot in managing precious resources like a connection

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
try
Dim n As Integer = 0
str = "select Vote from vote where party='Green'"
cmd = New SqlCommand(str, con)
con.Open()
dr.Close()
dr = cmd.ExecuteReader()
if dr.HasRows Then
dr.Read()
n = dr("Vote").ToString()
n = n + 1
Label8.Text = n.ToString()
End If
str = "update Vote set vote='" + n.ToString() + "' where party='Green'"
cmd = New SqlCommand(str, con)
cmd.ExecuteNonQuery()
dr.Read()
Finally
cmd.Dispose()
con.Close()
End Try
End Sub

Add multiple active results set to your connection string as shown below
Example:
"Server=Server;Database=MyDatabase;Trusted_Connection=True;MultipleActiveResultSets=true;"

Related

Why I get this error in Vb.net while connecting mysql “Conversion from string to type ‘Double’ is not valid”?

I tried the equation separately. It worked. But after I joined, i got the error of conversion. My aim is to get MySql data to the vb.net So I can check some values and develop the project. I have to finish the project within one week and I don’t know how to finish this. If this seems easy please forgive me.
Imports MySql.Data.MySqlClient
Public Class Form3
Dim conn As MySqlConnection
Dim command As MySqlCommand
Dim cmd As MySqlCommand
Dim Da As New MySqlDataAdapter
Dim ds As New DataSet
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'To check whether the date is same
TextBox1.Text = System.DateTime.Now.ToString(("MM/dd/yyyy"))
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
conn = New MySqlConnection
conn.ConnectionString = "server=localhost;user=root;password=1234;database=attendance"
Dim reader As MySqlDataReader
Try
ds.Clear()
conn.Open()
'Checking Subject Now
cmd = New MySqlCommand("select Subject_Name from dateverification", conn)
Da = New MySqlDataAdapter(cmd)
Da.Fill(ds, "dateverification")
TextBox2.Text = ds.Tables(0).Rows(0).Item(0)
'Checking Todays Date
cmd = New MySqlCommand("select Today_Date from dateverification", conn)
Da = New MySqlDataAdapter(cmd)
Da.Fill(ds, "dateverification")
Label1.Text = ds.Tables(0).Rows(0).Item(0)
'Checking Count1
cmd = New MySqlCommand("select Count1 from dateverification", conn)
Da = New MySqlDataAdapter(cmd)
Da.Fill(ds, "dateverification")
Label2.Text = ds.Tables(0).Rows(0).Item(0)
'Checking Count2
cmd = New MySqlCommand("select Count2 from dateverification", conn)
Da = New MySqlDataAdapter(cmd)
Da.Fill(ds, "dateverification")
Label3.Text = ds.Tables(0).Rows(0).Item(0)
'If the days are Different, Total days will be counted and Date will be updated
If Label1.Text <> TextBox1.Text Then
Label1.Text = System.DateTime.Now.ToString(("yyyy-MM-dd"))
Label2.Text = Label2.Text + 1
Dim query1 As String
query1 = "UPDATE attendance.dateverification SET Today_Date = '" & Label1.Text & "' , Count1 = '" & Label2.Text & "' WHERE Subject_Name = '" & TextBox3.Text & "'; "
command = New MySqlCommand(query1, conn)
reader = command.ExecuteReader
MessageBox.Show("Welcome to New Day")
Else
'If the date are equal, then the number of counts which register wasopen in same day will be increased
Label3.Text = Label3.Text + 1
Dim query1 As String
query1 = "UPDATE attendance.dateverification SET Count2 = '" & Label3.Text & "' WHERE Subject_Name = '" & TextBox3.Text & "'; "
command = New MySqlCommand(query1, conn)
reader = command.ExecuteReader
MessageBox.Show("You are still on the same day")
End If
Dim query As String
query = "UPDATE attendance.dateverification SET Subject_selected = '" & TextBox3.Text & "' WHERE Subject_Name = '" & TextBox3.Text & "'; "
command = New MySqlCommand(query, conn)
reader = command.ExecuteReader
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
Probably, the error is because this code is not always legal:
Label3.Text = Label3.Text + 1
Label3.Text is a string. Depending on compiler options, you can't just expect the compiler to convert it to a number for you. Those options are there to help you, and you should use them.
Moving on.
Not 100% sure on MySql, but in Sql Server for sure you could do all this as one connection command job in the database. This will perform better, and helped me greatly simplify the code.
Pay special attention to how I used parameters. It's NEVER okay to use string concatenation to put parameter values into a query. This is too important even for learning or proof of concept code.
Option Strict On
Option Infer On
Imports System
Imports MySql.Data.MySqlClient
Public Class Form3
'Don't try to keep the connection/command objects at the form level!
'Do keep the connection string here:
Private ConnectionString As String = "server=localhost;user=root;password=1234;database=attendance"
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = Today.ToString("MM/dd/yyyy")
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim conn As SqlConnection
'I put two statements in one command string,
' and the CASE expressions let me get all of the updates into one statement
Dim sql As String =
"UPDATE attendance.dateverification
SET Count1 = CASE WHEN Today_Date <> current_date THEN Count1 + 1 ELSE Count1 END,
Count2 = CASE WHEN Today_Date = current_date THEN Count2 + 1 ELSE Count2 END,
Today_Date = current_date,
Subject_selected = #subject
WHERE Subject_Name = #subject;
SELECT Subject_Name, Today_Date, Count1, Count2
FROM dateverification"
' Also note: this string could be a constant if we wanted to!
Try
conn = New MySqlConnection(ConnectionString)
Dim cmd As New MySqlCommand(sql, conn)
'Use actual type and length here
cmd.Parameters.Add("#subject", MySqlDbType.VarString, 50).Value = TextBox3.Text
conn.Open()
Dim rdr As MySqlDataReader = cmd.ExecuteReader()
rdr.Read()
TextBox2.Text = rdr("Subject_Name").ToString()
Label1.Text = rdr("Today_Date").ToString()
Label2.Text = rdr("Count1").ToString()
Label3.Text = rdr("Count2").ToString()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
End Class

Adapter update statement in oledb

I have a form with retrieved data form ms access database. While updating using the adapter update statement, it shows Syntax error.
The following are the connection code in form load event and update button click event.
could you please let me know whats wrong in this?
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\DESKTOP\VBATESTING\ADPE Project\Project Tables\ADPE_Table.accdb"
inc = 0
Dim Con As New OleDbConnection()
Dim Cmd As New OleDbCommand
Dim SQL As String = "SELECT * FROM Heidelberg"
Con.ConnectionString = strConn
Try
Con.Open()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Cmd = New OleDbCommand(SQL, Con)
Adapter.SelectCommand = New OleDbCommand(SQL, Con)
ds = New DataSet
Adapter.Fill(ds, "testing")
MaxRows = ds.Tables("testing").Rows.Count
Label1.Text = "Total Records :" & MaxRows
NavigateRecords()
End Sub
Private Sub UpdateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UpdateButton.Click
Dim cb As New OleDb.OleDbCommandBuilder(Adapter)
ds.Tables("testing").Rows(inc).Item(5) = TextBox1.Text
ds.Tables("testing").Rows(inc).Item(2) = TextBox2.Text
ds.Tables("testing").Rows(inc).Item(3) = TextBox3.Text
ds.Tables("testing").Rows(inc).Item(4) = TextBox4.Text
Try
Adapter.Update(ds, "testing")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
You have way too many commands in your Form.Load.
One
Dim Cmd As New OleDbCommand
Two
Cmd = New OleDbCommand(SQL, Con)
Three
Adapter.SelectCommand = New OleDbCommand(SQL, Con)
Every time you use the New keyword, you create another command.
If you are only dealing with a single table, you don't need a DataSet. The extra object adds extra weight and complicates the code a bit.
Private inc As Integer
Private Adapter As New OleDbDataAdapter
Private MaxRows As Integer
Private dat As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\DESKTOP\VBATESTING\ADPE Project\Project Tables\ADPE_Table.accdb"
inc = 0
Using Con As New OleDbConnection(strConn)
Using Cmd As New OleDbCommand("SELECT * FROM Heidelberg;", Con)
Adapter.SelectCommand = Cmd
Try
Adapter.Fill(dat)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Using
MaxRows = dat.Rows.Count
Label1.Text = "Total Records :" & MaxRows
NavigateRecords()
End Sub
Private Sub UpdateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UpdateButton.Click
dat.Rows(inc).Item(5) = TextBox1.Text
dat.Rows(inc).Item(2) = TextBox2.Text
dat.Rows(inc).Item(3) = TextBox3.Text
dat.Rows(inc).Item(4) = TextBox4.Text
Dim cb As New OleDbCommandBuilder(Adapter)
'This will take care of any spaces that you have in column names.
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
Try
Adapter.Update(dat)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

How to get UPDATE SQL commands working in VB.net and MySQL?

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim con As New MySqlConnection("host=localhost; username=root; password=; database=wh_db")
Dim cmd As New MySqlCommand
Dim dr As MySqlDataReader
con.Open()
cmd.Connection = con
cmd.CommandText = " select pass from user where pass ='" & oldpass.Text & "'"
dr = cmd.ExecuteReader
If dr.HasRows Then
cmd.Connection = con
cmd.CommandText = " UPDATE user SET pass ='" & newpass.Text & "' where user = '" & user.Text & "'"
Else
MsgBox("Password is not correct")
End If
End Sub
I've not used MySQL for a while but have a look at this. It should give you some start into what you're after:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dr As MySqlDataReader
Using con As New MySqlConnection(yourConnectionString),
cmd As New MySQLCommand("SELECT pass FROM user WHERE pass = #pass", con)
cmd.Parameters.Add("#pass", MySqlDbType.VarChar).Value = oldpass.Text
con.open()
dr = cmd.ExecuteReader
End Using
If dr.HasRows Then
Using con As New MySqlConnection(yourConnectionString),
cmd As New MySQLCommand("UPDATE user SET pass = #pass WHERE user = #user", con)
cmd.Parameters.Add("#pass", MySqlDbType.VarChar).Value = newpass.Text
cmd.Parameters.Add("#user", MySqlDbType.VarChar).Value = user.Text
con.open()
cmd.ExecuteNonQuery()
End Using
Else
MsgBox("Password is not correct")
End If
End Sub
The reason you're not updating is because you haven't told the command to update. I've also implemented Using which I suggest you do and also look at parameters to stop SQL injection.
I've separated both statements into two Using statements as I feel this would be better rather than attempting to reuse the same object for both the SELECT and UPDATE command.

Connect to sql server

Public Class Form1
Private Sub btnlogin_Click(sender As Object, e As EventArgs) Handles btnlogin.Click
Dim con As New SqlClient.SqlConnection(MYConnection.MYconnectionString)
con.Open()
Dim dr As SqlClient.SqlDataReader
Dim cmd As New SqlClient.SqlCommand("select * from [User] where UserName=" + txtuser.Text + " and UserPass= " + txtpassword.Text + "", con)
dr = cmd.ExecuteReader
If dr.Read Then
MsgBox("Welcome")
End If
con.Close()
End Sub
End Class
This is my code from my login form.. whenever i run the program and enter my username and password this will happen :
This is MyConnection.vb that i use to connect to my database
Public Class MYConnection
Public Shared MYconnectionString As String = "Server=CLAIRETUMLOS\SQLEXPRESS;Database=Capstone;Integrated Security=True;"
End Class
here is my dbo.User table
You are missing a ' for string field, but i advise you to use Parameters to avoid SQL injections, like this:
Private Sub btnlogin_Click(sender As Object, e As EventArgs) Handles btnlogin.Click
Dim con As New SqlClient.SqlConnection(MYConnection.MYconnectionString)
con.Open()
Dim dr As SqlClient.SqlDataReader
Dim cmd As New SqlClient.SqlCommand("select * from [User] where UserName=#UserName and UserPass=#UserPass", con)
cmd.Parameters.AddWithValue("#UserName", txtuser.Text)
cmd.Parameters.AddWithValue("#UserPass", txtpassword.Text)
dr = cmd.ExecuteReader
If dr.Read Then
MsgBox("Welcome")
End If
con.Close()
End Sub

specified cast is not valid

Here is a code that retrieve values from the database, but my problem is that it throws out an exception saying "InvalidCastException was unhandled specified cast is not valid". I am now confused what went wrong, The code and the table stated below.
Here is the code:
Public connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source =" & Application.StartupPath &
"\TestData.accdb; Persist Security info = false"
Public Conn As New OleDbConnection
Private Sub TestForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Loard
Conn.ConnectionString = connstring
Conn.Open()
LoadValue( )
End Sub
Private Sub LoadValue( )
Dim i As Integer
Dim cmd As OleDbCommand = New OleDbCommand
With cmd
.CommandText = "SELECT MAX(Guard_ID) FROM Guard"
.CommandType = CommandType.Text
.Connection = Conn
.ExecuteNonQuery()
Dim reader As OleDbDataReader = cmd.ExecuteReader
If reader.Read Then
TextBox1.Text = reader.GetString(0)
i = TextBox1.Text + 1
TextBox1.Text = i
reader.Close()
End If
End With
End Sub
The table reference:
Exception Error:
I am really confused now on why the code does not work, any help and advice will be gladly accepted. Thanks in advance.
try this,
Private Sub LoadValue()
Dim i As Integer
Dim cmd As OleDbCommand = New OleDbCommand
With cmd
.CommandText = "SELECT MAX(Guard_ID) FROM Guard"
.CommandType = CommandType.Text
.Connection = Conn
.ExecuteNonQuery()
Dim reader As OleDbDataReader = cmd.ExecuteReader
If reader.Read Then
Dim tmpVal As Object = reader.Item(0)
TextBox1.Text = IIf(IsDBNull(tmpVal), "0", tmpVal.ToString())
i = CInt(TextBox1.Text) + 1
TextBox1.Text = i.ToString()
reader.Close()
End If
End With
End Sub