How to display message if no records found - mysql

This is my code in filtering data into TextBoxes/Labels
Dim reader As MySqlDataReader
Try
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim query As String
query = "SELECT * FROM member WHERE (memor = '" & memor.Text & "')"
sqlcom = New MySqlCommand(query, conn)
reader = sqlcom.ExecuteReader
While reader.Read()
Me.lblname.Text = reader("membname").ToString
Me.txtmembtype.Text = reader("membtype").ToString
Me.lblmembdate.Text = reader("membdate").ToString
End While
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
Now I want to have a message box that prompts that there is no data found in my mysql database? Any idea?

You can simply use reader.HasRows() to check for records
reader = sqlcom.ExecuteReader
if Reader.HasRows() Then
While reader.Read()
Me.lblname.Text = reader("membname").ToString
Me.txtmembtype.Text = reader("membtype").ToString
Me.lblmembdate.Text = reader("membdate").ToString
End While
Else
MessageBox.Show("No records found")
End If

Beaten, but still posting for the obligatory SQL parameterization warning.
Revised code:
Try
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim query As String
query = "SELECT * FROM member WHERE (memor = #memor)"
sqlcom = New MySqlCommand(query, conn)
sqlcom.Parameters.AddWithValue("#memor", memor.Text)
reader = sqlcom.ExecuteReader
If reader.HasRows Then
While reader.Read()
Me.lblname.Text = reader("membname").ToString
Me.txtmembtype.Text = reader("membtype").ToString
Me.lblmembdate.Text = reader("membdate").ToString
End While
Else
MsgBox("No data found.")
End If
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try

Related

There is already an open Data Reader associated with this connection which must be closed first vb.net.vb

Dim Conn As MySqlConnection
Dim Command As MySqlCommand
Dim Reader As MySqlDataReader
Dim server As String = "serverxxxxxxxx.1;user=root;database=xxxxxxxxx"
Public Sub testing()
Conn = New MySqlConnection
Conn.ConnectionString = server
Dim datecompare As String = Date.Today.ToString("yyyy-MM-dd hh:mm:ss")
Dim primarykey1 As String = ""
Dim primarykey2 As String = ""
Try
If Not Conn.State = ConnectionState.Open Then
Conn.Open()
End If
Dim Query1 As String
Query1 = "Select * From `tblborrow` Where `DueDate` = '" & datecompare & "'"
Command = New MySqlCommand(Query1, Conn)
Reader = Command.ExecuteReader
While Reader.Read
primarykey1 = Reader.GetInt32("BorrowID")
Try
If Not Conn.State = ConnectionState.Open Then
Conn.Open()
End If
Dim query2 As String
query2 = "Update `tblborrow` Set `Remarks` = '" & "Due Date" & "' Where `BorrowID` = '" & primarykey1 & "'"
Command = New MySqlCommand(query2, Conn)
Reader = Command.ExecuteReader
Reader.Close()
Conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
'end of duedate
End While
Reader.Close()
Conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
'for OVER DUE
Try
If Not Conn.State = ConnectionState.Open Then
Conn.Open()
End If
Dim Query1 As String
Query1 = "Select * From `tblborrow` Where `DueDate` < '" & datecompare & "'"
Command = New MySqlCommand(Query1, Conn)
Reader = Command.ExecuteReader
While Reader.Read
primarykey2 = Reader.GetInt32("BorrowID")
Try
If Not Conn.State = ConnectionState.Open Then
Conn.Open()
End If
Dim query2 As String
query2 = "Update `tblborrow` Set `Remarks` = '" & "Over Due" & "' Where `BorrowID` = '" & primarykey2 & "'"
Command = New MySqlCommand(query2, Conn)
Reader = Command.ExecuteReader
Reader.Close()
Conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
'end of Over Due
End While
Reader.Close()
Conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Call testing()
End Sub
I created a public sub that will select and update the Remarks in my database based on the borrowID(this is auto increment). The save date in DueDate and compare i declare with the current time today, but every time i click the button where i saved the code i get this error There is already an openDataReaderassociated with this connection which must be closed first
i double checked my code and didn't miss to put reader.close() after every conn.close() or i don't know maybe i missed..
i tried some several changes in my code but still i get the same error.
can some help me and build my code? .. thanks.
Try to use different variable for the readers, maybe Reader1 and Reader2.
It's probably because you used the same reader to execute different query hence the already open datareader error.
You try to open the same book which is already open. At least make it a different book.
You are attempting to open 2 readers on a single connection. See the double headed arrows.
Reader = Command.ExecuteReader'<<----
While Reader.Read
primarykey1 = Reader.GetInt32("BorrowID")
Try
If Not Conn.State = ConnectionState.Open Then
Conn.Open()
End If
Dim query2 As String
query2 = "Update `tblborrow` Set `Remarks` = '" & "Due Date" & "' Where `BorrowID` = '" & primarykey1 & "'"
Command = New MySqlCommand(query2, Conn)
Reader = Command.ExecuteReader '<<----
If you break your code into logical units with only a single thing happening in each method it is a bit easier to see where things go wrong.
Keeping your database objects local to the methods where they are used allows you to be sure they are closed and disposed. Using...End Using blocks handle this for you even if there is an error.
Notice, in the 2 Update methods, the parameters are added outside the For loop and only the value that changes is set inside the loop.
Dim ConString As String = "serverxxxxxxxx.1;user=root;database=xxxxxxxxx"
Public Sub GetPKs()
Dim pkList As New List(Of Integer)
Dim DueDate As String = Date.Today.ToString("yyyy-MM-dd hh:mm:ss")
Using Conn As New MySqlConnection(ConString),
cmd As New MySqlCommand("Select BorrowID From tblborrow Where DueDate = #DueDate")
cmd.Parameters.Add("#DueDate", MySqlDbType.VarChar, 100).Value = DueDate
Conn.Open()
Using reader As MySqlDataReader = cmd.ExecuteReader
While reader.Read
pkList.Add(reader.GetInt32("BorrowID"))
End While
End Using
End Using
UpdateRemarks(pkList, DueDate)
End Sub
Private Sub UpdateRemarks(pks As List(Of Integer), DueDate As String)
Using con As New MySqlConnection(ConString),
cmd As New MySqlCommand("Update tblborrow Set Remarks = #DueDate Where BorrowID = #PK", con)
With cmd.Parameters
.Add("#DueDate", MySqlDbType.VarChar, 100).Value = DueDate
.Add("#PK", MySqlDbType.Int32)
End With
con.Open()
For Each i In pks
cmd.Parameters("#PK").Value = i
cmd.ExecuteNonQuery()
Next
End Using
End Sub
Private Sub GetOverduePKs()
Dim pkList As New List(Of Integer)
Using cn As New MySqlConnection(ConString),
cmd As New MySqlCommand("Select BorrowID From tblborrow Where DueDate < #DueDate")
cmd.Parameters.Add("#DueDate", MySqlDbType.VarChar, 100).Value = Date.Today.ToString("yyyy-MM-dd hh:mm:ss")
cn.Open()
Using reader = cmd.ExecuteReader
While reader.Read
pkList.Add(reader.GetInt32("BorrowID"))
End While
End Using
End Using
UpdateOverdueRemarks(pkList)
End Sub
Private Sub UpdateOverdueRemarks(pks As List(Of Integer))
Using cn As New MySqlConnection(ConString),
cmd As New MySqlCommand("Update tblborrow Set Remarks = 'Over Due' Where BorrowID = #PK")
cmd.Parameters.Add("#PK", MySqlDbType.Int32)
cn.Open()
For Each i In pks
cmd.Parameters("#PK").Value = i
cmd.ExecuteNonQuery()
Next
End Using
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
GetPKs()
GetOverduePKs()
End Sub
use 2 connections CONN and CONN2, with the same parameters, use CONN to open the QUERY1 reader. While reading, use CONN2 to create the 2nd query. Note that this works for MySQL. MS-Access can handle multiple commands in one connection, MySql cannot and needs separate connections. Sqlite cannot handle 2 simultanuos connections. there you have to use in incore temporary array or list. From a working program:
Dim DbConn As New MySqlConnection(SqlProv)
Dim DbConn2 As New MySqlConnection(SqlProv)
-
Dim SQLsfSelect As String = "SELECT CollSeq FROM ToBeIndexed WHERE CollCode = #CollCode"
Dim DRsfSelect As MySqlDataReader = Nothing
Dim DCsfSelect As MySqlCommand
Dim sfSelP1 As New MySqlParameter("#CollCode", MySqlDbType.VarChar, 4)
DCsfSelect = New MySqlCommand(SQLsfSelect, DbConn)
-
Dim SQLasSelect As String = "SELECT DISTINCT CollSeq FROM Data WHERE CollCode = #CollCode ORDER BY CollSeq"
Dim DRasSelect As MySqlDataReader = Nothing
Dim DCasSelect As MySqlCommand
Dim asSelP1 As New MySqlParameter("#CollCode", MySqlDbType.VarChar, 4)
DCasSelect = New MySqlCommand(SQLasSelect, DbConn2)
-
DbConn.Open()
sfSelP1.Value = CurCollCode
CollSeqToIdxC.Clear()
Try
DRsfSelect = DCsfSelect.ExecuteReader()
Do While (DRsfSelect.Read())
CollSeq = GetDbIntegerValue(DRsfSelect, 0)
DbConn2.Open()
asSelP1.Value = CurCollCode
Try
DRasSelect = DCasSelect.ExecuteReader()
Do While (DRasSelect.Read())
CollSeq = GetDbIntegerValue(DRasSelect, 0)
CollSeqToIdxC.Add(CollSeq, CStr(CollSeq))
Loop
Catch ex As Exception
MsgBox(ex.ToString(), , SysMsg1p(402, CurCollCode))
Finally
If Not (DRasSelect Is Nothing) Then
DRasSelect.Close()
End If
End Try
DbConn2.Close()
Loop
Catch ex As Exception
MsgBox(ex.ToString(), , SysMsg1p(403, CurCollCode))
Finally
If Not (DRsfSelect Is Nothing) Then
DRsfSelect.Close()
End If
End Try
DbConn.Close()

Bold database dates in MonthCalendar

I am trying to make my calendar number bold when there is an event saved into that specific date. I have searched and tried to do it but i cant.
How can i make the date bold when i saved an event into that selected date?
Here's what i tried to do but it cant convert to 1 dimensional array of date.
mydbcon = New MySqlConnection
mydbcon.ConnectionString = "server=localhost;userid=root;password=root;database=database"
Dim reader As MySqlDataReader
Dim bold = Form4.MonthCalendar1.SelectionRange.Start.Month
Try
mydbcon.Open()
Dim Query As String
Query = "Insert into database.calendar (eventname,Date,Time,Description) Values ('" & TextBox2.Text & "','" & Form4.MonthCalendar1.SelectionRange.Start & "','" & ComboBox1.SelectedItem & "','" & TextBox1.Text & "')"
COMMAND = New MySqlCommand(Query, mydbcon)
reader = COMMAND.ExecuteReader
MessageBox.Show("Event Succesfully Saved")
Form4.MonthCalendar1.BoldedDates = bold
mydbcon.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
mydbcon.Dispose()
End Try
Adding bold date to calendar - example:
MonthCalendar1.AddBoldedDate(CDate("03-12-2015"))
MonthCalendar1.UpdateBoldedDates()
Read dates from database - example:
mydbcon = New MySqlConnection
mydbcon.ConnectionString = "server=localhost;userid=root;password=root;database=database"
Dim reader As MySqlDataReader
Try
mydbcon.Open()
Dim Query As New MySql.Data.MySqlClient.MySqlCommand
Dim eventDate As String
Query.Connection = mydbcon
Query.CommandText = "SELECT Date FROM database ORDER BY Date"
reader = Query.ExecuteReader
If reader.HasRows = True Then
While reader.Read
eventDate = reader.GetValue(reader.GetOrdinal("Date")).ToShortDateString
MonthCalendar1.AddBoldedDate(CDate(eventDate))
End While
reader.Close()
MonthCalendar1.UpdateBoldedDates()
End If
mydbcon.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
mydbcon.Dispose()
End Try

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

speed of populating listview using mysql in vb.net

This is my code for populating the listview:
Dim itms As ListViewItem
Dim itm As New List(Of ListViewItem)
Dim itemcoll(2) As String
Dim strQ As String = String.Empty
strQ = "SELECT COLOR_CODE,DESC from COLORS"
cmd = New MySqlCommand(strQ, con)
Try
con.Open()
rs = cmd.ExecuteReader
lstview.Items.Clear()
Application.DoEvents()
lstview.SuspendLayout()
lstview.BeginUpdate()
lstview.Visible = False
While rs.Read
itemcoll(0) = IIf(Not IsDBNull(rs.Item("COLOR_CODE")), rs.Item("COLOR_CODE"), 0)
itemcoll(1) = IIf(Not IsDBNull(rs.Item("DESC")), rs.Item("DESC"), 0)
itms = New ListViewItem(itemcoll)
'lstview.Items.Add(itms)
itm.Add(itms)
End While
rs.Close()
lstview.Items.AddRange(itm.ToArray)
lstview.EndUpdate()
lstview.Visible = True
lstview.ResumeLayout()
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
This code is fast for populating rows of 10,000+, but If I am populating more than 50, 000, it is slow, it take 2 seconds to populate the listview, is the speed normal or slow?
And also what are the other techniques to speed up populating? I have use some of the ways to increase the speep of populating.
Thanks for the help.
Try this sample. Sometimes unnecessarily writing to placeholder variables can slow performance, though theoretically not much should be different in execution time.
Dim itm As New List(Of ListViewItem)
Dim strQ As String = "SELECT COLOR_CODE,DESC from COLORS"
cmd = New MySqlCommand(strQ, con)
lstview.Items.Clear()
Application.DoEvents()
lstview.SuspendLayout()
lstview.BeginUpdate()
lstview.Visible = False
Try
con.Open()
rs = cmd.ExecuteReader
While rs.Read
itm.Add(New ListViewItem({Convert.ToString(rs.Item("COLOR_CODE")),
Convert.ToString(rs.Item("DESC"))}))
End While
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
lstview.Items.AddRange(itm)
lstview.EndUpdate()
lstview.Visible = True
lstview.ResumeLayout()
End Try

MySQL Select Response Size .NET

Is it possible to receive the size of a MySQL response before reading it? To be able to have a progressbar giving status about the receiving process.
Public Function QUERY(ByVal queryString As String, ByVal connection As MySqlConnection)
Try
Dim newQuery As String() = Split(queryString, ":")
For Each Query In newQuery
Dim cmd As New MySqlCommand(Query, connection)
Dim reader As MySqlDataReader
reader = cmd.ExecuteReader()
While reader.Read()
End While
reader.Close()
Next
Catch ex As Exception
console("Error: " & ex.Message)
Return ex.Message
End Try
Return ""
End Function
No, using a DataReader you cannot know the number of records returned by your query until you reach the end of the reader. However you could use multiple statements in your query where the first statement is a count of your data.
This is a possible example:
using con = new MySqlConnection("your_connection_string")
con.Open()
Dim cmd As MySqlCommand = new SqlCommand("SELECT COUNT(*) FROM MyTable;" & _
"SELECT * FROM MyTable", con)
Dim dr as MySqlDataReader = cmd.ExecuteReader()
if dr.HasRows Then
dr.Read()
Dim count = Convert.ToInt32(dr(0))
Console.WriteLine("Reading:" & count.ToString() & " records")
dr.NextResult()
while dr.Read()
Console.WriteLine("Record:" + dr(dr.GetOrdinal("TableID")).ToString())
End While
End if
End Using