How to use DISTINCT Keyword in mySQL using VB.Net
How to use DISTINCT Keyword in mySQL using VB.Net.
In this tutorial, you will learn how to use the DISTINCT keyword using VB.Net.
First, we are going to create a database named distincttable. Then, we will add a table.
On your XAMPP Control Panel, click your database and click the SQL category to insert this line of code to create a table with columns:
Next, we are going to add values to our table. Click your student table and then click the SQL category to insert this line of code:
Next, create your VB project and drag a datagridview. Take note that you need the Mysql.Data.dll to access the mySQL methods. Also, set your datagridview AutoSizeColumnsMode to “Fill”.
Add the Mysql.Data.dll to your reference to access the mySQL methods and parameters.
At your Form1 designer, double click it and add this line of code:
- Imports MySql.Data.MySqlClient
- Public Class Form1
- Dim conn As MySqlConnection
- Dim cmd As MySqlCommand
- Dim da As MySqlDataAdapter
- Dim dt As DataTable
- Dim sql As String
- Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
- conn = New MySqlConnection
- conn.ConnectionString = "server=localhost; userid=root; password=; database=distincttable;"
- sql = "SELECT * FROM student;"
- cmd = New MySqlCommand(sql, conn)
- da = New MySqlDataAdapter
- dt = New DataTable
- da.SelectCommand = cmd
- DataGridView1.DataSource = dt
- Catch ex As MySqlException
- End Try
- End Sub
- End Class
Run your system and your expected output should be like this:
Now, as expected we have duplicate values in the Fullname and Address columns. In order to just show up at least one value representing them, we are going to use the DISTINCT keyword of mySQL.
DISTINCT is used to return only one value from duplicate values. This is helpful especially when you want to just get the list of values without duplication.
Now, we are going to change our sql string and add the DISTINCT keyword.
- sql = "SELECT DISTINCT Fullname, Address FROM student;"
Load again your project and you will see the results that you can only see one value from different same values.
Congratulations! You have learned today how to use DISTINCT keyword in mySQL using VB.Net.
For questions or any other concerns or thesis/capstone creation with documentation, you can contact me through the following:
E-Mail: [email protected]
Contact No.: +639771069640
Ian Hero L. Lavapiez
System Analyst and Developer
Related topic(s) that you may like:
- Limiting Data Selection Query in mySQL
- Populate Multiple Data to ListView from mySQL database using VB.Net