VB.Net program to insert a record in the MySql database

Here, we are going to learn how to insert a record in the MySql database in VB.Net?
Submitted by Nidhi, on February 09, 2021 [Last updated : March 08, 2023]

Prerequisites: Need to install MySQL server and MySQL connector.

VB.Net – Insert Record in MySQL table

In this program, here we will connect to the MySQL database and then insert a record into the "employee" table.

Program/Source Code:

The source code to insert a record in the MySql database is given below. The given program is compiled and executed successfully.

VB.Net code to insert a record in the MySql database

'VB.NET program to insert a record in MySql database.

Imports MySql.Data.MySqlClient

Module Module1
    Sub Main()
        Dim connString As String
        'Connection String to connect with MySQL database.
        connString = "server=localhost;userid=root;password=root;database=sampledb"

        Dim conn As New MySqlConnection(connString)

        Dim InsertCommand As String

        InsertCommand = "INSERT INTO employee(eid,ename, salary) VALUES(@eid,@ename,@salary)"

        Dim cmd = New MySqlCommand(InsertCommand, conn)

        cmd.Parameters.AddWithValue("@eid", 101)
        cmd.Parameters.AddWithValue("@ename", "Amit Kumar")
        cmd.Parameters.AddWithValue("@salary", 43200)

        Console.WriteLine("Record inserted successfully")
    End Sub
End Module


Record inserted successfully
Press any key to continue . . .


In the above program, we imported a namespace MySql.Data.MySqlClient to establish the connection with the MySql database. Then we created a module Module1 that contains a Main() function.

The Main() function is the entry point for the program. In the Main() function, we created a connection string variable ConnString that contains the database connectivity credentials. After that we established the connection to the MySql database using MySqlConnection class and then insert a record into the "employee" table using ExecuteNonQuery() method of MySqlCommand class and then print the "Record inserted successfully" message on the console screen.

VB.Net Database Connectivity Programs »

Comments and Discussions!

Copyright © 2023 www.includehelp.com. All rights reserved.