MySQL Select Response Size .NET - mysql

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

Related

reading and comparing data values in MySQL database in vb.net

I'm trying to collect input from the user, check it against my database, and see if it exists in the database. If it does the program is supposed to fetch the last name, first name, and fees of the respective individual and output it.
Code:
Imports Mysql.Data.MySqlClient
Public Class Form1
Dim reader As MySqlDataReader
Dim command As New MySqlCommand
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myConnectionString As String
myConnectionString = "server=localhost;" _
& "uid=root;" _
& "pwd=Emma#21*GCTU;" _
& "database=dummystudents"
Try
Dim conn As New MySql.Data.MySqlClient.MySqlConnection(myConnectionString)
conn.Open()
Dim sql As String = "SELECT idstudents FROM students WHERE idstudents = #TextBox1.Text "
command = New MySqlCommand(sql, conn)
reader = command.ExecuteReader()
If reader.Read() Then
TextBox2.Text = reader(1)
TextBox3.Text = reader(2)
TextBox4.Text = reader(3)
End If
Catch ex As MySql.Data.MySqlClient.MySqlException
MessageBox.Show(ex.Message)
End Try
End Sub
End Class
Here's your SQL code:
SELECT idstudents FROM students WHERE idstudents = #TextBox1.Text
What's the point of pulling idstudents out when that's the value you're putting in? Worse, though, that's ALL you're pulling out, then you do this:
TextBox2.Text = reader(1)
TextBox3.Text = reader(2)
TextBox4.Text = reader(3)
which would require you to pull back at least four columns.
The modification mentioned in the comments may well get your code to execute but it's not the right way to go. It looks like you tried to use a parameter but failed. Do that but do it right, i.e.
Dim sql As String = "SELECT idstudents, otherColumnsHere FROM students WHERE idstudents = #idstudents"
Using connection As New MySqlConnection(myConnectionString),
command As New MySqlCommand(sql, connection)
command.Parameters.Add("#idstudents", MySqlDbType.Int32).Value = CInt(TextBox1.Text)
conn.Open()
Using reader = command.ExecuteReader()
If reader.Read() Then
TextBox2.Text = reader(1)
TextBox3.Text = reader(2)
TextBox4.Text = reader(3)
End If
End Using
End Using

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()

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

vb.net/mysql show more then 1 row in TextBox

I just started messing around with Visual basic (vb.net) and am trying to show more then 1 database row in a TextBox, so far I have this:
Private Sub foobox_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim conn As MySqlConnection
conn = New MySqlConnection
conn.ConnectionString = connStr
Try
conn.Open()
Catch myerror As MySqlException
MsgBox("No connection")
End Try
Dim myAdaptor As New MySqlDataAdapter
Dim sqlquery = "SELECT * FROM foo ORDER BY id DESC"
Dim myCommand As New MySqlCommand()
myCommand.Connection = conn
myCommand.CommandText = sqlquery
myAdaptor.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader()
If myData.HasRows Then
myData.Read()
Viewer.Text = myData("foo1") & myData("foo2")
End If
myData.Close()
conn.Close()
End Sub
which connects to a database successfully but but it only outputs 1 row, how can I get it to output more?
You need a loop reading data and storing line after line in a StringBuilder.
Then, when exiting from the reading loop set the Text property of your textbox
Dim sb as StringBuilder = new StringBuilder()
While myData.Read()
sb.AppendLine(myData("foo1") & myData("foo2"))
End While
Viewer.Text = sb.ToString
and, of course, your textbox should have the MultiLine property set to True
Apart from this direct answer to your question, your code should be changed to dispose the connection and the datareader after use, I have also removed the DataAdapter because is not needed here
Using conn = New MySqlConnection(connStr)
Try
conn.Open()
Catch myerror As MySqlException
MsgBox("No connection")
End Try
Dim sqlquery = "SELECT * FROM foo ORDER BY id DESC"
Dim myCommand As New SqlCommand(sqlquery, conn)
Using myData = myCommand.ExecuteReader()
Dim sb as StringBuilder = new StringBuilder()
While myData.Read()
sb.AppendLine(myData("foo1") & myData("foo2"))
End While
Viewer.Text = sb.ToString
End Using
End Using
You need some kind of loop. I would also use the Using statement to ensure that all unmanaged resources are disposed even in case of an exception(it also closes the connection):
Using conn As New MySqlConnection(connStr)
Using myCommand As New MySqlCommand("SELECT * FROM foo ORDER BY id DESC", conn)
Try
conn.Open()
Using myData = myCommand.ExecuteReader()
If myData.HasRows Then
While myData.Read()
Dim line = String.Format("{0}{1}{2}",
myData.GetString(myData.GetOrdinal("foo1")),
myData.GetString(myData.GetOrdinal("foo1")),
Environment.NewLine)
viewer.Text &= line
End While
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Using
End Using
However, if you want to show multiple records i would recommend a ListBox instead. It's more efficient with many items and it also separates them logical from each other.
( just replace viewer.Text &= line with ListBox1.Items.Add(line) )

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.