Part II: Inserting and Reading of Data in MySQL Database Using Visual Basic.Net

This tutorial is the continuation of Connecting MySQL Database using Visual Basic.NET. In this part we will focus on how to insert Data and to load data and display it in a form using DataGridview Object. To start with, we will set up first our database table. To do this make sure that you have installed XAMPP this software is free and open source cross-platform web server solution stack package, consisting mainly of the Apache HTTP Server, MySQL database, and interpreters for scripts written in the PHP and Pearl programming languages. If not installed you can download it to the web and install it into your computer. After you have successfully installed it on your computer just simply run the Apache Server and MySQL database using the XAMPP Control Panel Application. Next step open any browser available in your local computer. For example “google chrome” and on the address bar just type http://localhost/phpmyadmin/ and press enter. After this on the List of the Database then Select “test” Database as default the test database don’t have any table(s) available inside it. And on the “menus” Select the SQL tab and paste this code:
  1. CREATE TABLE `test`.`users` (
  2. `fullname` VARCHAR( 30 ) NOT NULL ,
  3. `username` VARCHAR( 30 ) NOT NULL ,
  4. `password` VARCHAR( 50 ) NOT NULL
  5. ) ENGINE = MYISAM ;
So this code will create a table named “users” and it has a field such as user_id, fullname, username and password. Now the users table will look like as shown below. Now it’s time to proceed to our main goal of this tutorial, to do this let’s open the first Part and the title of this is “Connecting MySQL Database using Visual Basic.Net” and the project name of this is “VBMYSQL”. After this step Go to Solution Explorer->right click the Project name->Click Add->Select Windows Form and automatically new form will open and the default name of this is “Form2”.

Designing the User Interface

In the User Interface just add two Buttons, three Textbox, three Labels, one Groupbox and one Datagridview.

Object			Property			Settings

Form2			Name				manage_user
			Text				Manage User
Button1   		Name				btncreate
			Text				Create User
Button2   		Name				btnRead
			Text				Read User
Textbox1		Name				txtfullname
Textbox2		Name				txtusername
Textbox3		Name				txtpassword
Label1   		Text				Full Name
Label2  		Text				Username		
Label3			Text				Password
GroupBox1		Text				User Info
DataGridView1		Name				dtguser
And the design looks like as shown below. Hence we have designed our User Interface let’s proceed to add functionality one of our button specifically the “Create User”, to do this just Double Click “Create User” button after this you be redirected to the code view. And add again we’re going to do something we have done in our first tutorial that we put an Imports MySql.Data.MySqlClient above Public class so that we can have access to our MySQL Objects. Then we need also to copy and paste our declaration of our object the MySqlConnection Dim con As New MySqlConnection and together with this declaration we need also to add declaration and the code now will like as shown below.
  1. Imports MySql.Data.MySqlClient
  2. Public Class Manage_user
  3.     Dim con As New MySqlConnection
  4.     Dim result As Integer
  5.  
  6.     'MySqlCommand It represents a SQL statement to execute against a MySQL Database
  7.     Dim cmd As New MySqlCommand
  8. Next will add code to our btncreate button and here’s the code.
  9. Private Sub btncreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncreate.Click
  10.         'this line of is simply we copy this one from our form
  11.         con.ConnectionString = ("server=localhost;user id=root;password=;database=test")
  12.  
  13.         Try
  14.             'we open Connection
  15.             con.Open()
  16.  
  17.             With cmd
  18.                 .Connection = con
  19.                 .CommandText = "INSERT INTO `test`.`users` (`user_id`, `fullname`, `username`, `password`) " & _
  20.                                 "VALUES (NULL, '" & txtfullname.Text & "', '" & txtusername.Text & "', '" & txtpassword.Text & "');"
  21.                 'in this line it Executes a transact-SQL statements against the connection and returns the number of rows affected
  22.                 result = cmd.ExecuteNonQuery
  23.                 'if the result is equal to zero it means that no rows is inserted or somethings wrong during the execution
  24.                 If result = 0 Then
  25.                     MsgBox("Data has been Inserted!")
  26.                 Else
  27.                     MsgBox("Successfully saved!")
  28.  
  29.                 End If
  30.             End With
  31.         Catch ex As Exception
  32.             MsgBox(ex.Message)
  33.         End Try
  34.         con.Close()
  35.     End Sub
This time we will try to test if our code is working properly. But before this, we need to set first that when the program runs it run first the “Manage User” Form. To do this, Go to Solution Explorer->right click and select Properties. And on the properties choose the “Application Tab” and under the “Startup form” choose the “manage_user” like as shown below. Then just press f5 to run your application. And you test it by writing something in the textbox provided and after just simply click “Create User” button. After this you can view the result in phpmyadmin if you really successfully saved your user inputted. So we are designing and adding of code to our “Create User” we only need is to display all the user saved in the database to our datagridview. To do this, double click “Read user” and Add this code.
  1.  Private Sub btnload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnload.Click
  2.         'again we do this because we do not yet declare this as global, but we do it for now beacause in later tutorial
  3.         'we will do the moduling and more on refactoring of codes
  4.         con.ConnectionString = ("server=localhost;user id=root;password=;database=test")
  5.         Try
  6.             con.Open()
  7.             With cmd
  8.                 .Connection = con
  9.                 'in this query it does simply selecting or getting all the user found in the database.
  10.                 .CommandText = "Select * from users"
  11.             End With
  12.  
  13.         Catch ex As Exception
  14.             MsgBox(ex.Message)
  15.  
  16.  
  17.         End Try
  18.         con.Close()
  19.         da.Dispose()
  20.         filltable(dtguser)
  21.  
  22.     End Sub
After this add another sub procedure like this.
  1. ' this our sub procedure that well always used
  2.     'this beacause it always catch all the result query
  3.     'and it will display to any kind of visual basic containers like datagridview,listbox,listview, etc...
  4.     Public Sub filltable(ByVal dtgrd As Object)
  5.         'declare a variable as new datatable
  6.         Dim publictable As New DataTable
  7.         Try
  8.             'Gets or sets an SQL statement or stored procedure used to select records in the database.
  9.             da.SelectCommand = cmd
  10.             da.Fill(publictable)
  11.             dtgrd.DataSource = publictable
  12.             dtgrd.Columns(0).Visible = False
  13.  
  14.             da.Dispose()
  15.  
  16.         Catch ex As Exception
  17.             MsgBox(ex.Message)
  18.  
  19.         End Try
  20.  
  21.     End Sub
And finally try to run your application and the final output will be look like as shown below. these are all the source code in this tutorial.
  1. Imports MySql.Data.MySqlClient
  2. Public Class Manage_user
  3.     Dim con As New MySqlConnection
  4.     Dim result As Integer
  5.     'MySqlCommand It represents a SQL statement to execute against a MySQL Database
  6.     Dim cmd As New MySqlCommand
  7.     'Represents a set of data commands and a database connection that
  8.     'are used to fill a dataset and update a MySQL database. This class cannot be inherited.
  9.     Dim da As New MySqlDataAdapter
  10.  
  11.     Private Sub btncreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncreate.Click
  12.         'this line of is simply we copy this one from our form
  13.         con.ConnectionString = ("server=localhost;user id=root;password=;database=test")
  14.  
  15.         Try
  16.             'we open Connection
  17.             con.Open()
  18.  
  19.             With cmd
  20.                 .Connection = con
  21.                 .CommandText = "INSERT INTO `test`.`users` (`user_id`, `fullname`, `username`, `password`) " & _
  22.                                 "VALUES (NULL, '" & txtfullname.Text & "', '" & txtusername.Text & "', '" & txtpassword.Text & "');"
  23.                 'in this line it Executes a transact-SQL statements against the connection and returns the number of rows affected
  24.                 result = cmd.ExecuteNonQuery
  25.                 'if the result is equal to zero it means that no rows is inserted or somethings wrong during the execution
  26.                 If result = 0 Then
  27.                     MsgBox("Data has been Inserted!")
  28.                 Else
  29.                     MsgBox("Successfully saved!")
  30.  
  31.                 End If
  32.             End With
  33.         Catch ex As Exception
  34.             MsgBox(ex.Message)
  35.         End Try
  36.         con.Close()
  37.     End Sub
  38.  
  39.     Private Sub btnload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnload.Click
  40.         'again we do this because we do not yet declare this as global, but we do it for now beacause in later tutorial
  41.         'we will do the moduling and more on refactoring of codes
  42.         con.ConnectionString = ("server=localhost;user id=root;password=;database=test")
  43.         Try
  44.             con.Open()
  45.             With cmd
  46.                 .Connection = con
  47.                 'in this query it does simply selecting or getting all the user found in the database.
  48.                 .CommandText = "Select * from users"
  49.             End With
  50.  
  51.         Catch ex As Exception
  52.             MsgBox(ex.Message)
  53.  
  54.  
  55.         End Try
  56.         con.Close()
  57.         da.Dispose()
  58.         filltable(dtguser)
  59.  
  60.     End Sub
  61.     ' this our sub procedure that well always used
  62.     'this beacause it always catch all the result query
  63.     'and it will display to any kind of visual basic containers like datagridview,listbox,listview, etc...
  64.     Public Sub filltable(ByVal dtgrd As Object)
  65.         'declare a variable as new datatable
  66.         Dim publictable As New DataTable
  67.         Try
  68.             'Gets or sets an SQL statement or stored procedure used to select records in the database.
  69.             da.SelectCommand = cmd
  70.             da.Fill(publictable)
  71.             dtgrd.DataSource = publictable
  72.             dtgrd.Columns(0).Visible = False
  73.  
  74.             da.Dispose()
  75.  
  76.         Catch ex As Exception
  77.             MsgBox(ex.Message)
  78.  
  79.         End Try
  80.  
  81.     End Sub
  82. End Class
So that is for now folks. My Part III of my Tutorial will be focusing on completing the User CRUD or the CREATE, READ, UPDATE AND DELETE.

Comments

why have error on dtguser?

In reply to by wawi (not verified)

change the name of your datagridview to dtguser or whatever name you like.

bakit coco martin yung pangalang inilagay mu? hahaha

How to rebind the datagridview's database values

how to solve problem with listbox after run the program n save date ...when i try to read the system.data.datarowview appear

what is the declaration of the variable da?

Add new comment