data reader in vb.net - mysql

Please help, how do I make a while loop equivalent of this for loop. So that I could read from one row in the table of mysql database and display it on the combobox in vb.net.
I use this code, but its definitely not useful if there are 3 or more items that are added in the row:
Dim i As Integer
Dim rdr As Odbc.OdbcDataReader
rdr = con.readfrom_drug_type_table()
For i = 0 To 1
If rdr.HasRows = True Then
rdr.Read()
ComboBox2.Items.Add(rdr("Drug_type"))
End If
Next i
I want to read all the data from that the Drug_type row
Please help, thanks

If you want to read only first row than just use
If rdr.Read() Then
ComboBox2.Items.Add(rdr("Drug_type"))
End If
Update
Try
myConnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=pubs")
'you need to provide password for sql server
myConnection.Open()
myCommand = New SqlCommand("Select * from discounts", myConnection)
dr = myCommand.ExecuteReader
While dr.Read()
WriteLine(dr(0))
WriteLine(dr(1))
WriteLine(dr(2))
WriteLine(dr(3))
WriteLine(dr(4))
' writing to console
End While
Catch
End Try
dr.Close()
myConnection.Close()

#pranay
You don't need the nested loops.
Try
myConnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=pubs")
myConnection.Open()
myCommand = New SqlCommand("Select * from discounts", myConnection)
dr = myCommand.ExecuteReader()
While dr.Read()
WriteLine(dr(0))
WriteLine(dr(1))
WriteLine(dr(2))
WriteLine(dr(3))
WriteLine(dr(4))
End While
dr.Close()
Finally
myConnection.Close()
End Try

Related

VB.Net Delete Selected Row in DataGridView MySql

This the code that I use. The message box is appearing but when I select yes, the selected row is not deleted at the datagridview and database.
Private Sub Delete2_Click_1(sender As Object, e As EventArgs) Handles Delete2.Click
MySqlConn = New MySqlConnection
MySqlConn.ConnectionString = "server=127.0.0.1;userid=root;password=;database=equipment"
Try
If Me.DataGridView2.Rows.Count > 0 Then
If Me.DataGridView2.SelectedRows.Count > 0 Then
Dim intStdID As Char = Me.DataGridView2.SelectedRows(0).Cells("asset_code").Value
'open connection
If Not MySqlConn.State = ConnectionState.Open Then
MySqlConn.Open()
End If
'delete data
Dim cmd As New MySqlCommand
cmd.Connection = MySqlConn
cmd.CommandText = "DELETE * FROM equipment.equipment" & intStdID
Dim res As DialogResult
res = MsgBox("Are you sure you want to DELETE the selected Row?", MessageBoxButtons.YesNo)
If res = Windows.Forms.DialogResult.Yes Then
cmd.ExecuteNonQuery()
Else : Exit Sub
End If
'refresh data
Load_table()
'close connection
MySqlConn.Close()
End If
End If
Catch ex As MySqlException
End Try
Look at this line:
cmd.CommandText = "DELETE * FROM equipment.equipment" & intStdID
It attempts to append the ID value from the selected cell to the SQL statement. However, it seems like this is just the ID value. You also need the WHERE ID= portion for the query.
Moreover, it's using this ID value in the query in the wrong way. It's NEVER okay to use string concatenation to include data in a query. You must use parameterized queries.
The code below demonstrates this, as well as several other better patterns for this method, with the caveat that I had to guess as some names and types from your database.
Private Sub Delete2_Click_1(sender As Object, e As EventArgs) Handles Delete2.Click
If Me.DataGridView2.Rows.Count = 0 OrElse Me.DataGridView2.SelectedRows.Count = 0 Then
Exit Sub
End If
Dim res As DialogResult = MsgBox("Are you sure you want to DELETE the selected Row?", MessageBoxButtons.YesNo)
If res <> DialogResult.Yes Then Exit Sub
Dim intStdID As Char = Me.DataGridView2.SelectedRows(0).Cells("asset_code").Value
Dim SQL as String = "DELETE * FROM equipment.equipment WHERE equipment.StdID= #AssetCode"
Using con As New MySqlConnection("server=127.0.0.1;userid=root;password=;database=equipment"), _
cmd As New MySqlCommand(SQL, con)
cmd.Parameters.Add("#AssetCode", MySqlDbType.VarChar, 1).Value = intStdID
con.Open()
cmd.ExecuteNonQuery()
End Using
Load_table()
End Sub

SELECT MAX(value) from table VB.net

I have this table that contains multiple values all ranging from 1 to 3000, but it keep retuning false.
What is going wrong here?
Dim connectionString As String = "Server=**; Uid=**; Pwd=**; Database=**"
Using SQLConnection As New MySqlConnection(connectionString)
Using sqlCommand As New MySqlCommand()
With sqlCommand
.CommandText = "SELECT MAX(CAST(points AS UNSIGNED)) FROM score"
.Connection = SQLConnection
.CommandType = CommandType.Text
End With
Try
SQLConnection.Open()
Using reader As MySqlDataReader = sqlCommand.ExecuteReader
While (reader.Read())
label1.Text = reader.Read()
End While
End Using
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
Finally
SQLConnection.Close()
End Try
End Using
End Using
Probably you need to read the field not calling again Read
label1.Text = reader(0).ToString()
However, to read a scalar value like you do, it is preferable to use the ExecuteScalar method. It returns just the single value of your query without creating an MySqlDataReader and all the infrastructure needed when you want to read more than one record one by one
Using sqlCommand As New MySqlCommand()
With sqlCommand
.CommandText = "SELECT MAX(CAST(points AS UNSIGNED)) FROM score"
.Connection = SQLConnection
.CommandType = CommandType.Text
End With
Try
SQLConnection.Open()
Dim result = Convert.ToInt64(sqlCommand.ExecuteScalar())
label1.Text = result.ToString()
.....
Read() advances to the next row/result (and returns a boolean indicating if you've passed the end of the result set); you're looking for GetInt32() or similar methods.

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

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

Grab a Column in MySQL in VB.NET

I have just learned MySQL in VB.NET, but I am having a complication..
When I grab a SELECT Query, I want to get - lets say the 'username' column in each row it receives. How would I do that?
MySQL.CommandText = "SELECT * FROM online"
MySQL.ExecuteNonQuery()
Label1.Text = 'usernamehere'
Thanks :)
Public Sub CreateMySqlDataReader(mySelectQuery As String, myConnection As MySqlConnection)
Dim myCommand As New MySqlCommand(mySelectQuery, myConnection)
myConnection.Open()
Dim myReader As MySqlDataReader
myReader = myCommand.ExecuteReader()
Try
While myReader.Read()
Console.WriteLine(myReader.GetString(0))
End While
Finally
myReader.Close
myConnection.Close
End Try
End Sub
Found on: http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqlcommand.html#connector-net-examples-mysqlcommand-executereader
Also as a bonus. If you are going to throw in some parameters in that query I would suggest you look into prepared statements.