How to insert data to a MySQL table in Java

Hello friends, today I am going to show you how to insert data to a MySQL table by using Java. One of my previous post describe this same job under PHP. Also I have explained how to connect with a MySQL database in Java. Actually I am using the same code sample here with some differences.

The first difference is, today I am showing all the Exception sub-classes which I have hidden in my previous post due to present you a clear and simple code sample. The obvious difference is that I have add lines of codes which perform the insert data function.

I don’t try to explain the process in here because I have used comments with in my code sample to describe what I have done. Therefore let’s jump to the code directly.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

 * @author Anuja
public class Insert {

    public static void main(String[] args) {
        // A connection (session) with a specific database.
        // SQL statements are executed and results are returned within the context of a connection.
        Connection conn = null;

        String dbUserName = "root"; // MySQL database username
        String dbPassword = ""; // MySQL database password
        // Actually dbUrl variable can be divided into three categories for understanding purpose
        // "jdbc:mysql://" is a required syntax to create the connection with MySQL
        // "localhost/" this part is the "datadir" attribute that we have defined within my.ini file
        // I am using WAMP server 2.1 and you can see the above attribute in line 39 within my.ini file
        // "test" this is the name of my database. You can define this as a different variable too.
        String dbUrl = "jdbc:mysql://localhost/test";

        try {
            // forName() method is static.
            // It returns the Class object associated with the class or interface with the given string name.
            Class forNam = Class.forName("com.mysql.jdbc.Driver");

            try {
                // newInstance() creates a new instance of the class represented by this Class object
            } catch (InstantiationException ex) {
                Logger.getLogger(Insert.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(Insert.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Insert.class.getName()).log(Level.SEVERE, null, ex);

        try {
            // DriverManager is the basic service for managing a set of JDBC drivers.
            // getConnection() attempts to establish a connection to the given database URL
            conn = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
            System.out.println("Database connection establish...!");

            Statement st = conn.createStatement();
            String insertSql = "INSERT test_full_name VALUES(" + 4 + "," + "'Anuj'" +  "," + "'Arosh'" + ")";
            // If we are going to insert a Duplicate entry for PRIMARYKEY, we will get an exception
            // com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException
            int val = st.executeUpdate(insertSql);
            System.out.println("One raw get affected...");

        } catch (SQLException ex) {
            System.out.println("Cannot connect to database server...!!");
            Logger.getLogger(Insert.class.getName()).log(Level.SEVERE, null, ex);
        } finally{
            if(conn != null){
                try {
                    // close() releases this Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released.
                    System.out.println ("Database connection terminated...!!!");
                } catch (SQLException ex) {
                    Logger.getLogger(Insert.class.getName()).log(Level.SEVERE, null, ex);

I hope if you copy this code in to an IDE will give you a clear understand of the scenario. Before you run this code make sure to start your web server with MySQL enable.

I have created a database called “test” by using phpmyadmin and there is one table called “test_full_name“.  That table consist with three fields called “id“, “firstName” and “lastName“.

I think that’s all you need to run this program perfectly. The initial steps of how to connect with MySQL database was described under “Compare connecting MySQL database in Java and PHP” post.

Thank You for visiting here 🙂


About AnujAroshA

Working as a Senior Software Engineer. Specialized in iOS application development. A simple person :)
This entry was posted in Java. Bookmark the permalink.

3 Responses to How to insert data to a MySQL table in Java

  1. great effort, and valuable work, i appreciate those who share his/her knowledge with other

  2. Sagar Poudel says:

    Thanks bro…………

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s