Retrieving Data in MySQL Database Using DataReader in VB.Net

Today you will learn on how to retrieve data in MySQL Database using DataReader in VB.net. This method provides an effective way to retrieve data from the database. It is efficient to use this kind of method because you can design the datagridview column according to your desire.

Let’s get started:

Create a database and name it, “peopledb
  1. CREATE DATABASE peopledb;
After creating database, add a table in it.
  1. CREATE TABLE `tbluser` (
  2.   `UserId` int(11) NOT NULL,
  3.   `Fullname` varchar(124) NOT NULL
After adding a table, insert a data in the table that you have created
  1. INSERT INTO `tbluser` (`UserId`, `Fullname`) VALUES
  2. (1, 'Janno Palacios'),
  3. (2, 'Craig'),
  4. (3, 'cherry lou velez'),
  5. (4, 'velez lou'),
  6. (5, 'jom');
Open Microsoft Visual Studio 2015 and create a new windows form application. After that, do the Windows Form just like shown below. ps1 This time, go to the code view and do the following codes above the Public Class for your imports.
  1. Imports MySql.Data.MySqlClient
After that, do the following codes below the Public Class to declare all the classes that are needed. Then, initialize your MySQL Connection
  1. Dim con As New MySqlConnection("server=localhost;user id=root;Password=janobe;database=peopledb")
  2.     Dim cmd As MySqlCommand
  3.     Dim dr As MySqlDataReader
  4.     Dim sql As String
Go back to the Design View and double click the button in the form to fire the click event handler of it. Do the following code for retrieving data in the MySQL database.
  1. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  2.         Try
  3.             con.Open()
  4.             sql = "SELECT * FROM `tbluser`"
  5.             cmd = New MySqlCommand
  6.             With cmd
  7.                 .Connection = con
  8.                 .CommandText = sql
  9.             End With
  10.             dr = cmd.ExecuteReader()
  11.             DataGridView1.Rows.Clear()
  12.             Do While dr.Read = True
  13.                 DataGridView1.Rows.Add(dr(0), dr(1))
  14.             Loop
  15.         Catch ex As Exception
  16.             MsgBox(ex.Message)
  17.         Finally
  18.             con.Close()
  19.         End Try
  20.     End Sub
Press f5 to run your project If you find an error, please download mysql-connector-net-6.4.4.msi and install it on your machine. Add the MySQL.Data.dll as a reference for the project that you have created. You can download the complete source code and run it on your computer For more question about this article. You can contact me @ Email – [email protected] Mobile No. – 09305235027 – TNT FB Account – https://www.facebook.com/onnaj.soicalap

Comments

Thank you very much, it helped me a lot!

Add new comment