How do I insert a record into database table?

In this example you’ll learn how to create a program to insert data into a database table. To insert a data we need to get connected to a database. After a connection is obtained you can create a java.sql.Statement object from it, and using this object we can execute some query string.

package org.kodejava.example.sql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class SelectStatementSample {
    public static void main(String[] args) throws Exception {
        Connection connection = null;
        try {
            // Register MySQL JDBC driver class.
            Class.forName("com.mysql.jdbc.Driver");

            // Get a connection to database.
            String url = "jdbc:mysql://localhost/kodejava";
            String user = "kodejava";
            String password = "kodejava123";
            connection = DriverManager.getConnection(url, user, password);

            // Create a statement object.
            Statement stmt = connection.createStatement();

            String sql = "INSERT INTO m_users (username, first_name, " +
                    "last_name, address) VALUES ('fbar', 'Foo', " +
                    "'Bar', 'Sunset Road 123')";

            // Call an execute method in the statement object 
            // and pass the query.
            stmt.execute(sql);
        } catch (ClassNotFoundException e) {
            System.err.println("Could not load database driver!");
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.close();
            }
        }
    }
}

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.

Leave a Reply