Mysql & Vb.net 'Invalid Attempt to Read when reader is closed' - mysql

I have run into this error while collecting data from a mysql database and placing it into a DataView control... This is my code:
Private Function PopulateActivity()
Dim loginStatement As String = "SELECT * FROM activity WHERE id = #userid"
Dim cmd As MySqlCommand = New MySqlCommand(loginStatement, mainconn)
cmd.Parameters.AddWithValue("#userid", LoggedInUser.ID)
Dim drMyAcount As MySqlDataReader = cmd.ExecuteReader()
Dim rowCount As Integer = 0
Dim rowAmount As Integer = 0
'gets count of rows returned from mysql query'
Using dt As New DataTable
dt.Load(drMyAcount)
rowAmount = dt.Rows.Count
End Using
'adds an entry for each item returned from the mysql query'
Do While rowCount < rowAmount
drMyAcount.Read() 'HERE IS WHERE ERROR OCCURS'
Dim tempDateTime As String = drMyAcount.Item("dateTime")
Dim tempInfo As String = drMyAcount.Item("info")
Dim tempBalChanges As String = drMyAcount.Item("balChange")
Dim tempToFrom As String = drMyAcount.Item("toFrom")
ActivityView.Rows.Add(tempDateTime, tempInfo, tempBalChanges, tempToFrom)
rowCount = rowCount + 1
Loop
drMyAcount.Close()
Return 0
End Function
I am unaware of why this is but it gives me an 'Invalid Attempt to Read when reader is closed' error one the:
drMyAccount.Read()
line...
I would appreciate any help on this topic! Thanks Much...

take out the dt.Load() , and counting of the rows prior to using datareader. DataReader has a built in property of .HasRows
if (drMyAcount.HasRows)
while (drMyAcount.Read())
Dim tempDateTime As String = drMyAcount.Item("dateTime")
Dim tempInfo As String = drMyAcount.Item("info")
Dim tempBalChanges As String = drMyAcount.Item("balChange")
Dim tempToFrom As String = drMyAcount.Item("toFrom")
ActivityView.Rows.Add(tempDateTime, tempInfo, tempBalChanges, tempToFrom)
rowCount = rowCount + 1 //you can still count rows in the loop
Loop

The MSDN documentation does not seem to specify, but apparently the DataTable.Load method closes the given IDataReader when it is done loading the data into the table. So, once you call dt.Load(drMyAcount), the drMyAcount will be closed.

Related

VB.NET MySQL : Error 'Unable to cast object of type 'System.Int32' to type 'MySql.Data.MySqlClient.MySqlDataReader

I have trouble with my coding below :
Private Function NoCustID() As String
Dim drtmp As MySqlDataReader
Dim mySqlCmd As New MySqlCommand
Dim sTmp As String
Dim nStr As String
dbConn.Open()
sTmp = "SELECT * FROM tbnomor WHERE ftipe=1 AND UPPER(fnama)='CUSTOMER'"
mySqlCmd = New MySqlCommand(sTmp, dbConn)
drtmp = mySqlCmd.ExecuteScalar()
nStr = drtmp("fprefix").ToString & "-" & String.Format(drtmp("ftempno").ToString, "0000")
dbConn.Close()
Return nStr
End Function
Error raised on Line With ExecuteScalar(), where the error code as shown above title.
I don't know what mistake.
Please help, thanks
Change drtmp = mySqlCmd.ExecuteScalar() to drtmp = mySqlCmd.ExecuteReader().
The method ExecuteScalar() returns the first column of the first row in the result and ignore others. In this instance, the returned column is integer data type, and not an array.
Use:
drtmp = mySqlCmd.ExecuteReader()
While drtmp.Read()
nStr = drtmp("fprefix").ToString & "-" & String.Format(drtmp("ftempno").ToString, "0000")
End While
Don't declare connections outside of the method where they are used. Both connections and commands need to be disposed. Using...End Using blocks handle this for us.
Don't open the connection until directly before the .Execute...
.ExecuteScalar is used to return a single piece of data. You need .ExecuteReader to return a DataReader.
Don't process data until the connection is closed with End Using.
I filled a DataTable so your could process the data after the connection is closed. Readers require an open connection.
Private ConStr As String = "Your connection string"
Private Function NoCustID() As String
Dim dt As New DataTable
Using dbConn As New MySqlConnection(ConStr),
mySqlCmd As New MySqlCommand("SELECT * FROM tbnomor WHERE ftipe=1 AND UPPER(fnama)='CUSTOMER'", dbConn)
dbConn.Open()
Using drtmp = mySqlCmd.ExecuteReader
dt.Load(drtmp)
End Using
End Using
Dim nStr = $"{dt(0)("fprefix")} - {dt(0)("ftempno"):0000}"
Return nStr
End Function

how to use FIND_IN_SET with dataview.rowfilter in vb.net

I'm using this code to filter my datatable by dataview:
Dim xBlockedAccounts As String = "1,5,7"
Dim xDv_AllAcc As New DataView(MyVar_Dt_Accounts)
xDv_AllAcc.RowFilter = "FIND_IN_SET(AccID," & xBlockedAccounts & ")"
Me.Dgv3.DataSource = xDv_AllAcc.ToTable
but it gives me that:
The expression contains undefined function call FIND_IN_SET().'
how I can use FIND_IN_SET function with Rowfilter of Dataview?
I assumed MyVar_Dt_Accounts was a DataTable. You need to have an array of blocked accounts values. Then the Linq magic.
Private Sub OPCode()
Dim MyVar_Dt_Accounts As New DataTable
Dim xBlockedAccounts = {"1", "5", "7"}
Dim dt = (From row As DataRow In MyVar_Dt_Accounts.AsEnumerable
Select row
Where xBlockedAccounts.Contains(row("AccID").ToString)).CopyToDataTable
Dgv3.DataSource = dt
End Sub
Check first that AccID is really a string in the database and not a number.

How to read a value from mysql database?

I want to be able to read a value (in this case an Group ID). All the topics and tutorials I've watched/read take the data and put it into a textbox.
I don't want to put it in a textbox in this case; I want to grab the Group ID and then say:
If Group ID = 4 then login
Here is an image of the database.
Basically, but none of the tutorials I watch or the multiple forums. None of them take a a value and say if value = 4 then login or do something else.
If text = "1" Then
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString =
"server='ip of server'.; username=; password=; database="
Dim READER As MySqlDataReader
Dim member_group_id As String
Try
MysqlConn.Open()
Dim Query As String
Query = "SELECT * FROM `core_members` where name='" & TextBox2.Text & "'"
Query = "SELECT * FROM `nexus_licensekeys` where lkey_key='" & TextBox1.Text & "'"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
Dim count As Integer
count = 0
While READER.Read
count = count + 1
End While
Here is what I have so far. I'm kind of new implementing mysql data with visual basic and only recently started to get into it. I'm not sure what comes next or how to even start with reading the group id etc.
As I said any help from here on out would be highly appreciated of how to read the group id and say if this group id = this number then do this or that. I'm sure you get the idea.
I divided the code into UI Sub, and Data Access Function that can return data to the UI. Your Event procedure code should be rather brief and the functions should have a single purpose.
Keep your database objects local to the method. This way you can have better control. The Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error.
I leave it to you to add validation code. Checking for empty TextBox or no return of records.
I hope this serves as a quick introduction to using ADO.net. The take away is:
Use Parameters
Make sure connections are closed. (Using blocks)
Private ConnString As String = "server=ip of server; username=; password=; database="
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim GroupID As String = GetGroupID(TextBox1.Text)
If GroupID = "4" Then
'your code here
End If
Dim LocalTable As DataTable = GetLicenseKeysData(TextBox1.Text)
'Get the count
Dim RowCount As Integer = LocalTable.Rows.Count
'Display the data
DataGridView1.DataSource = LocalTable
End Sub
Private Function GetGroupID(InputName As String) As String
'Are you sure member_group_id is a String? Sure looks like it should be an Integer
Dim member_group_id As String = ""
'You can pass the connection string directly to the constructor of the connection
Using MysqlConn As New MySqlConnection(ConnString)
'If you only need the value of one field Select just the field not *
'ALWAYS use parameters. See comment by #djv concerning drop table
Using cmd As New MySqlCommand("SELECT g_id FROM core_members where name= #Name")
'The parameters are interperted by the server as a value and not executable code
'so even if a malicious user entered "drop table" it would not be executed.
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = InputName
MysqlConn.Open()
'ExecuteScalar returns the first column of the first row of the result set
member_group_id = cmd.ExecuteScalar.ToString
End Using
End Using
Return member_group_id
End Function
Private Function GetLicenseKeysData(InputName As String) As DataTable
Dim dt As New DataTable
Using cn As New MySqlConnection(ConnString)
Using cmd As New MySqlCommand("SELECT * FROM `nexus_licensekeys` where lkey_key= #Name;", cn)
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = InputName
cn.Open()
dt.Load(cmd.ExecuteReader())
End Using
End Using
Return dt
End Function

Vb.net auto generate string proxy for the value of .bytes as variable to be inserted in mysql

hi help me with this please? how can i change the value of .bytes as a auto generated string? and also to be inserted in my database
Dim myconn As MySqlConnection
myconn = New MySqlConnection
myconn.ConnectionString = "server=localhost; user id=root ; password=; database=auto"
myconn.Open()
Dim comm As New MySqlCommand
comm.Connection = myconn
comm.CommandText = "insert into sample(name,template) values (#name,#result)"
comm.Parameters.Add(New MySqlParameter("#name", nametxt.txt))
'i need to change the value of sample from bytes to unique auto generated strings
comm.Parameters.Add(New MySqlParameter("#result", sample.bytes))
comm.ExecuteNonQuery()
msgbox("success")
and through research i found this snippets
Functon RandomString()
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim r As New Random
Dim sb As New StringBuilder
For i As Integer = 1 To 8
Dim idx As Integer = r.Next(0, 35)
sb.Append(s.Substring(idx, 1))
Next
return sb.ToString()
End Function
but im getting an error at StringBuilder and i dont know how to implement it to my codes. so please help me modify and implement it to my codes. any help is much appreciated

Value Parameter changes to 0

I want to display the data based on the value of the desired user, I tried to use a parameter that contains the value from the input. When I run the program data can not be performed. I'm trying to find my fault location code, by checking the value of limit_kar that holds the result of input from the user are the contents of the corresponding results of the input, when the limit_kar value stored into parameter changed to 0, I think a lot of errors in my code, please suggesting that the problem this can be resolved
I'm using VS 2008 and mysql
thank you
Newbie
this is mycode
Public Function Tampil_Stock(ByVal limit_kar As Integer) As List(Of Class_stock)
Dim tmpBaca As New List(Of Class_stock)
Dim cmd As New MySqlCommand
Dim dreader As MySqlDataReader
Dim ds As New DataSet
Dim sql As String
sql = "SELECT NoReg,status_kartu FROM tb_stock WHERE status= '0' and status_kartu= '0' ORDER BY NoReg ASC Limit ?fn "
cmd = New MySqlCommand(sql, myconnection.open)
cmd.Parameters.Add(New MySqlParameter("?fn", MySqlDbType.Int64)).Value = **limit_kar**
dreader = cmd.ExecuteReader
If dreader.HasRows Then
While dreader.Read
Dim objTemp As New Class_stock
objTemp.NoReg_ = dreader.Item("NoReg")
'objTemp.NoPin_ = dreader.Item("NoPin")
'objTemp.status_ = dreader.Item("status")
objTemp.status_kartu_ = dreader.Item("status_kartu")
tmpBaca.Add(objTemp)
End While
Else
MsgBox("Not Found")
End If
myconnection.close()
Return tmpBaca
'dreader.Close()
End Function
The syntax of your parameter declaration is incorrect. Look at the example here : http://www.devart.com/dotconnect/mysql/docs/Parameters.html.
cmd.Parameters.Add(New MySqlParameter("?fn", MySqlDbType.Int64)).Value = limit_kar
This looks odd to me. Shouldn't Add take the value as parameter ? What is "?fn" ? Does Add really return the new MysqlParameter instance ?
The following sticks to the example from the docs. I still don't understand the reason why you are using ?fn and why you declare the type explicitly as MySqlDbType.Int64.
sql = "SELECT NoReg,status_kartu FROM tb_stock WHERE status= '0' and status_kartu= '0' ORDER BY NoReg ASC Limit ?"
cmd = New MySqlCommand(sql, myconnection.open)
cmd.Parameters.Add("limit_kar", limit_kar)