VB.NET reader is closed - vb.net

I have code which allows me to send an email to a customer using customer details in my database.
Try
mysqlconn.Open()
GetEmailCredentials(credentials)
query = "SELECT First_name, surname, email_address FROM customer,booking WHERE booking.BookingID='" & y & "' AND customer.customerID=booking.customerID"
command = New MySqlCommand(query, mysqlconn)
MsgBox("ref1")
reader = command.ExecuteReader
MsgBox("ref2")
While reader.Read()
MsgBox("ref3")
Try
MsgBox(reader.GetString("email_address") & reader.GetString("First_name") & reader.GetString("surname"))
MsgBox("ref4")
Dim emailmessage As New MailMessage()
emailmessage.From = New MailAddress(credentials(0))
emailmessage.To.Add(reader.GetString("email_address"))
emailmessage.Subject = "EHCC Booking"
emailmessage.Body = "Hello " & reader.GetString("First_name") & " " & reader.GetString("surname") & Environment.NewLine & "One of your bookings has been deleted." & Environment.NewLine & "Please contact me for further details."
Dim smtp As New SmtpClient("smtp.gmail.com")
smtp.Port = 587
smtp.EnableSsl = True
smtp.Credentials = New System.Net.NetworkCredential(credentials(0), credentials(1))
smtp.Send(emailmessage)
MsgBox("ref5")
Catch ex As Exception
errors.Enqueue("Email details are incorrect")
End Try
mysqlconn.Close()
End While
Catch ex As MySqlException
errors.Enqueue(ex.Message)
Finally
mysqlconn.Dispose()
End Try
I keep on getting the error message 'Invalid attempt to Read when reader is closed'.
I get all of the reference message boxes popping up, along with the one that outputs the results of the query. The query orks fine so i have no idea whats happening. I can't see anywhere where i have closed the reader, until i have closed the mysqlconnection.
Im sorry if my explanation is clear.

Change this
While reader.Read()
...
mysqlconn.Close()
End While
To this
While reader.Read()
...
End While
mysqlconn.Close()

Related

How to fix "Invalid attempt to read when reader is closed vb.net"

invalid attempt to read when reader is closed error. vb.net
I have the code below that I use to login into MySQL but it keeps displaying the error 'invalid attempt to read when reader is closed' and then it logs in. I don't understand what could still be wrong with the code. Kindly assist, it's so frustrating. Thanks.
Try
ConnDB()
command = con.CreateCommand()
command.CommandText = "SELECT UserName,Password,Type,EmpNo FROM userstable where UserName=#d1 and Password=#d2 and Active='Yes'"
command.Parameters.AddWithValue("#d1", txtUsername.Text)
command.Parameters.AddWithValue("#d2", txtPassword.Text)
Reader = command.ExecuteReader()
If Reader.Read = True Then
ComboBox1.Text = Reader.GetValue(2)
lblUser.Text = Reader.GetValue(3)
End If
If (Reader IsNot Nothing) Then
Reader.Close()
End If
If con.State = ConnectionState.Open Then
con.Close()
End If
If ComboBox1.Text.Length > 0 Then
MainMenu.lblUserName.Text = Me.txtUsername.Text
MainMenu.lblType.Text = Me.ComboBox1.Text
MainMenu.lblOccupation.Text = Me.ComboBox1.Text
MainMenu.lblUser.Text = Me.lblUser.Text
Dim st As String = "Successfully logged in"
LogFunc(txtUsername.Text, st)
Me.Hide()
MainMenu.Show()
Else
MsgBox("Incorrect username or password..Login is Failed...Try again !", MsgBoxStyle.Critical, "Login")
txtUsername.SelectAll()
txtPassword.SelectAll()
txtUsername.Focus()
txtPassword.Text = ""
End If
command.Dispose()
' Reader.Close()
'command.Dispose()
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
DisconnMy()
End Try
I expect it to log in successfully without displaying the error.
Sorry, I forgot to add this for my connection string.
Public Sub ConnDB()
con.Close()
Try
con.ConnectionString = "Server = '" & ServerMySQL & "'; " _
& "Port = '" & PortMySQL & "'; " _
& "Database = '" & DBNameMySQL & "'; " _
& "user id = '" & UserNameMySQL & "'; " _
& "password = '" & PwdMySQL & "'"
con.Open()
Catch ex As Exception
MsgBox("The system failed to establish a connection", MsgBoxStyle.Information, "Database Settings")
End Try
End Sub
In general it's not a good idea to use a "global", single connection for everything. Note that connection-pooling is enabled by default which means that .NET will take care of the physical connections. So you should create,open,use and close/dispose the connection where you use it.
I'm pretty sure that this will fix the issue:
Try
Using con As New MySql.Data.MySqlClient.MySqlConnection(MySettings.Default.SqlConnection)
Using command = con.CreateCommand()
command.CommandText = "SELECT UserName,Password,Type,EmpNo FROM userstable where UserName=#d1 and Password=#d2 and Active='Yes'"
command.Parameters.AddWithValue("#d1", txtUsername.Text)
command.Parameters.AddWithValue("#d2", txtPassword.Text)
con.Open()
Using reader = command.ExecuteReader()
If reader.Read() Then
ComboBox1.Text = reader.GetValue(2)
lblUser.Text = reader.GetValue(3)
End If
' NOTE: you dont need to close the reader/command/connection
' if you use the Using-statement, it will use Dispose even in case of an error
End Using
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

Insert into database in vb not working

I have the below snippet of code whenever I try registering the username exist part seems to be executed even for a username that doesn't exist in the database. Don't know where am wrong here any help will be appreciated.
'Connecting to SQL Database and executing Query------------------------------------------
Dim Strconn As String = "Data Source=.\SQLEXPRESS; Database=QuizDB; Integrated Security = true"
Dim Strcmd As String = "INSERT INTO reg_info(uname,pass,fname,lname,dob,course,college) VALUES ('" & user_name.Text & "','" & con_pass.Text & "', '" & first_name.Text & "', '" & last_name.Text & "', '" & dob.Text & "', '" & course.Text & "', '" & college.Text & "');"
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Dim sqlcmd As SqlCommand
sqlconn = New SqlConnection(Strconn)
Try
sqlconn.Open()
Catch ex As Exception
MsgBox("Could not connect to DataBase. Application will close now!", vbCritical, "Database Error")
End
End Try
sqlcmd = New SqlCommand(Strcmd, sqlconn)
da.SelectCommand = sqlcmd
sqlcmd.Dispose()
sqlconn.Close()
'Exception Handling-----------------------
Dim exc As Exception = Nothing
Try
da.Fill(ds)
Catch ex As Exception
exc = ex
Finally
If Not (exc) Is Nothing Then
MsgBox("User Name Already Exist. Please select a different User Name!", vbExclamation, "Already Exist")
user_name.Focus()
Else
MsgBox("Registration Successful.", vbInformation, "Successful")
Me.Close()
Login.Show()
End If
End Try
Here is a refactor of your code with some helpful guidance. I think this will compile, but if it does not, then you can do a little homework to figure out what is missing.
Try
' the USING block guarantees that the object's Close() and Dispose() methods are fired automatically when you exit the block
Using sqlconn As New SqlConnection("Data Source=.\SQLEXPRESS; Database=QuizDB; Integrated Security = true")
Using sqlcmd As SqlCommand = sqlconn.CreateCommand
With sqlcmd
.CommandType = CommandType.Text
' parameterized query to protect against SQL injection
.CommandText = "INSERT INTO reg_info(uname,pass,fname,lname,dob,course,college) VALUES (#username, #password, #firstname, #lastname, #dob, #course, #college)"
With .Parameters
.Clear()
.AddWithValue("#username", user_name.Text)
.AddWithValue("#password", con_pass.Text)
.AddWithValue("#firstname", first_name.Text)
.AddWithValue("#lastname", last_name.Text)
.AddWithValue("#dob", dob.Text)
.AddWithValue("#course", course.Text)
.AddWithValue("#college", college.Text)
End With
.ExecuteScalar() ' Actually executes the SQL command
End With
End Using
End Using
MsgBox("Registration successful")
Catch ex As Exception
' Any error in the TRY block will automatically jump to herem and the "ex" object will be an Exception object with populated properties
MsgBox("User name already exists. Error from database is " & ex.Message)
End Try

How to prevent certain data from being inserted into the database with If Else statements?

I have two comboboxes, a messagebox and a Send button. When the app startups and I click on the Send button with the comboboxes and messagebox empty, a pop-up box comes up and says "Select a client" After doing this, I go back to the database and see that it has added a new record to that table, even though I didn't put in any data after clicking on the "Send" button. Same applies for when one of the three controls I have has data in it, but the other two don't, and the program asks me to enter that data before it succeeds. But it still adds the record despite having those If Statements. What am I doing wrong?
My code:
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)
con.Open()
Using cmd As New SqlCommand
cmd.Connection = con
cmd.CommandText = "insert into tblMyTable(Client, UserName, Message) values('" & cboClient.Text & "', '" & cboUser.Text & "', '" & rtfMessage.Text & "')"
cmd.ExecuteNonQuery()
End Using
If cboClient.Text = "" Then
MsgBox("Select a client")
ElseIf cboUser.Text = "" Then
MsgBox("Select a user")
ElseIf rtfMessage.Text = "" Then
MsgBox("Enter a message")
Else
MsgBox("Message Sent")
End If
con.Close()
End Using
I think you want something like this (note this does not address parameterization concerns):
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)
If cboClient.Text = "" Then
MsgBox("Select a client")
ElseIf cboUser.Text = "" Then
MsgBox("Select a user")
ElseIf rtfMessage.Text = "" Then
MsgBox("Enter a message")
Else
con.Open()
Using cmd As New SqlCommand
cmd.Connection = con
cmd.CommandText = "insert into tblMyTable(Client, UserName, Message) values('" & cboClient.Text & "', '" & cboUser.Text & "', '" & rtfMessage.Text & "')"
cmd.ExecuteNonQuery()
End Using
MsgBox("Message Sent")
End If
con.Close()
End Using
Similar solution to #OldProgrammer, with an attempt at parameterized insert.
Private Sub SendButton_Click(sender As System.Object, e As System.EventArgs) Handles SendButton.Click
Try
If writeMessage() Then
MessageBox.Show("Message sent.", "Success")
End If
Catch ex As Exception
MessageBox.Show(String.Concat("An error occurred sending this message:", ex.Message))
End Try
End Sub
Private Function writeMessage() As Boolean
If isValidMessage() Then
writeMessageInfo()
Return True
End If
Return False
End Function
Private Sub writeMessageInfo()
Using con As New SqlConnection(yourConnectionString)
con.Open()
Using cmd As New SqlCommand
cmd.Connection = con
cmd.Parameters.Add(New SqlParameter("clientValue", cboClient.Text))
cmd.Parameters.Add(New SqlParameter("userValue", cboUser.Text))
cmd.Parameters.Add(New SqlParameter("messageText", rtfMessage.Text))
cmd.CommandText = "insert into tblMyTable(Client, UserName, Message) values(#clientValuem, #userValue, #messageText)"
cmd.ExecuteNonQuery()
End Using
con.Close()
End Using
End Sub
Private Function isValidMessage() As Boolean
If cboClient.SelectedIndex = -1 Then
MessageBox.Show("Please select a client.", "Missing info")
cboClient.Focus()
Return False
End If
If cboUser.SelectedIndex = -1 Then
MessageBox.Show("Please select a user.", "Missing info")
cboUser.Focus()
Return False
End If
If rtfMessage.Text = String.Empty Then
MessageBox.Show("Please enter a message.", "Missing info")
rtfMessage.Focus()
Return False
End If
Return True
End Function

count max records in web service

I want to count max records called srno from table called complaint in a database. How to write it in web service?
I am using this code
'open
Dim cmd18 As OleDbCommand
Try
'MsgBox("open")
cnn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\CRM.mdb")
cnn.Open()
msg = "select count(srno) from [Complaint] where [status]= '" & Me.RadButton6.Text & "'"
cmd18 = New OleDbCommand(msg, cnn)
str = cmd18.ExecuteScalar()
Catch ex As Exception
' MsgBox("No Records Inserted" + ex.ToString())
Finally
cnn.Close()
End Try
If str Is DBNull.Value Then
Button1.Text = "0"
Else
Button1.Text = Format(CStr(TextBox1.Text)) & Convert.ToInt32(str)
End If
i want in webservice..
You will find all your answers here http://www.asp.net/web-api

Error showing while updating database with Identity Column

Please help me... i am trying to update my database from VB.net. It shows error. My code is given below....
Try
getConnect()
Dim strSQL As String
strSQL = " UPDATE DEPARTMENT SET [DEP_ID]=#DEP_ID,[DEPART]=#DEPART, [DEP_DSCRPTN]=#DEP_DSCRPTN WHERE [DEP_ID] = #DEP_ID"
Dim cmd As New SqlCommand(strSQL, Conn)
cmd.Parameters.AddWithValue("#DEP_ID", CInt(Me.DEPID.Text))
cmd.Parameters.AddWithValue("#DEPART", SqlDbType.VarChar).Value = CMBDEPT.Text
cmd.Parameters.AddWithValue("#DEP_DSCRPTN", SqlDbType.VarChar).Value = TXTDESC.Text
Conn.Open()
cmd.ExecuteNonQuery()
MsgBox("Update Complete!", MsgBoxStyle.Information, "Update")
Catch ex As Exception
MsgBox("ERROR: " + ex.Message, MsgBoxStyle.Information, "Update")
Finally
Conn.Close()
BTNCLEAR.PerformClick()
End Try
And the error is:
ERROR: Cannot update identity column 'DEP_ID'
Remove [DEP_ID]=#DEP_ID, from the SET. It makes no sense to try and set it to the value already ensured by the WHERE anyway so it is clearly redundant and it is not permitted to update IDENTITY columns.
UPDATE DEPARTMENT
SET [DEPART] = #DEPART,
[DEP_DSCRPTN] = #DEP_DSCRPTN
WHERE [DEP_ID] = #DEP_ID
The error message is clear, remove the Set DEP_ID = #DEP_ID part.
Try
getConnect()
Dim strSQL As String
strSQL = "UPDATE DEPARTMENT SET [DEPART]=#DEPART," +
"[DEP_DSCRPTN]=#DEP_DSCRPTN WHERE [DEP_ID] = #DEP_ID"
Dim cmd As New SqlCommand(strSQL, Conn)
cmd.Parameters.AddWithValue("#DEP_ID", CInt(Me.DEPID.Text))
cmd.Parameters.AddWithValue("#DEPART", SqlDbType.VarChar).Value = CMBDEPT.Text
cmd.Parameters.AddWithValue("#DEP_DSCRPTN", SqlDbType.VarChar).Value = TXTDESC.Text
Conn.Open()
cmd.ExecuteNonQuery()
MsgBox("Update Complete!", MsgBoxStyle.Information, "Update")
Catch ex As Exception
MsgBox("ERROR: " + ex.Message, MsgBoxStyle.Information, "Update")
Finally
Conn.Close()
BTNCLEAR.PerformClick()
End Try
If you find yourself in need to change an Identity column then I think you need to analyze better your database schema.