JDBC SQL INSERT Query Example

In previous posts, we have learned about types of JDBC drivers and the how to make database connection using JDBC and then how to execute SELECT Query. Let’s move forward. In this example I am picking up execution of SQL INSERT queries using JDBC.

JDBC-Icon

SQL INSERT query are executed to push/store data stored in relational databases. It requires following steps:

1) Make a database connection
2) Execute the SQL INSERT Query

Pr-requisites include setting up a database schema and creating a table at least.

CREATE SCHEMA 'JDBCDemo' ;

CREATE  TABLE 'JDBCDemo'.'EMPLOYEE' 
(
  'ID' INT NOT NULL DEFAULT 0 ,
  'FIRST_NAME' VARCHAR(100) NOT NULL ,
  'LAST_NAME' VARCHAR(100) NULL ,
  'STAT_CD' TINYINT NOT NULL DEFAULT 0 
);

Let’s write above steps in code:

1) Make a database connection

Though we have already learned about it in making JDBC connection, lets recap with this simple code snippet.

Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager
	.getConnection("jdbc:mysql://localhost:3306/JDBCDemo", "root", "password");

2) Execute the SQL INSERT Query

This is the main step and core part in ths post. It requires creating a Statement object and then using it’s execute() method.

Statement stmt = connection.createStatement();
stmt.execute("INSERT INTO EMPLOYEE (ID,FIRST_NAME,LAST_NAME,STAT_CD) VALUES (1,'Lokesh','Gupta',5)");

Above statement will execute an insert statement in database we are connected to.

Let’s see the whole code in working.

package com.howtodoinjava.jdbc.demo;

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

public class InsertDataDemo {
	public static void main(String[] args) {
		Connection connection = null;
		Statement stmt = null;
		try 
		{
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager
				.getConnection("jdbc:mysql://localhost:3306/JDBCDemo", "root", "password");
			
			stmt = connection.createStatement();
			stmt.execute("INSERT INTO EMPLOYEE (ID,FIRST_NAME,LAST_NAME,STAT_CD) "
								+ "VALUES (1,'Lokesh','Gupta',5)");
		} 
		catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				stmt.close();
				connection.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

That’s all in this post. Drop me a comment if something needs explanation.

Happy Leaning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

5 thoughts on “JDBC SQL INSERT Query Example”

  1. what’s wrong with this code/*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    package com.myjava.string;

    import java.sql.*;
    import javax.swing.*;

    /**
    *
    * @author Eptl Maurai
    */
    public class Empdetail extends javax.swing.JFrame {
    Connection connection = null;
    Statement stmt = null;

    /**
    * Creates new form Empdetail
    */
    public Empdetail() {
    initComponents();

    // conn=javaconnect.Empdet();
    }

    /**
    * This method is called from within the constructor to initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is always
    * regenerated by the Form Editor.
    */
    @SuppressWarnings(“unchecked”)
    //
    private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    Empid = new javax.swing.JTextField();
    jLabel5 = new javax.swing.JLabel();
    jLabel1 = new javax.swing.JLabel();
    jLabel4 = new javax.swing.JLabel();
    Empname = new javax.swing.JTextField();
    Empcity = new javax.swing.JTextField();
    jLabel2 = new javax.swing.JLabel();
    Empsalary = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    jScrollPane1 = new javax.swing.JScrollPane();
    Empaddress = new javax.swing.JTextArea();
    jButton1 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, “Employee Details”, javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font(“Agency FB”, 1, 14))); // NOI18N

    Empid.setName(“”); // NOI18N
    Empid.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    EmpidActionPerformed(evt);
    }
    });

    jLabel5.setText(“Empcity”);

    jLabel1.setText(“Empid”);

    jLabel4.setText(“Empsalary”);

    Empname.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    EmpnameActionPerformed(evt);
    }
    });

    Empcity.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    EmpcityActionPerformed(evt);
    }
    });

    jLabel2.setText(“Empname”);

    Empsalary.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    EmpsalaryActionPerformed(evt);
    }
    });

    jLabel3.setText(“Empadress”);

    Empaddress.setColumns(20);
    Empaddress.setRows(5);
    jScrollPane1.setViewportView(Empaddress);

    jButton1.setText(“Submit”);
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    }
    });

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
    jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addGap(33, 33, 33)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jLabel3)
    .addComponent(jLabel5)
    .addComponent(jLabel4)
    .addComponent(jLabel2)
    .addComponent(jLabel1))
    .addGap(129, 129, 129)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(Empid, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(Empname, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(Empsalary, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(Empcity, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addContainerGap(53, Short.MAX_VALUE))
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addGap(182, 182, 182)
    .addComponent(jButton1)
    .addGap(0, 0, Short.MAX_VALUE))
    );
    jPanel1Layout.setVerticalGroup(
    jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addGap(23, 23, 23)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jLabel1)
    .addComponent(Empid, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGap(18, 18, 18)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jLabel2)
    .addComponent(Empname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGap(31, 31, 31)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addGap(37, 37, 37)
    .addComponent(jLabel3)))
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addGap(10, 10, 10)
    .addComponent(jLabel4))
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addGap(18, 18, 18)
    .addComponent(Empsalary, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 21, Short.MAX_VALUE)
    .addComponent(jLabel5)
    .addGap(63, 63, 63))
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addGap(18, 18, 18)
    .addComponent(Empcity, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
    .addComponent(jButton1)
    .addGap(5, 5, 5))
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(67, 67, 67)
    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(259, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(30, 30, 30)
    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(36, Short.MAX_VALUE))
    );

    pack();
    }//

    private void EmpsalaryActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:

    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

    // TODO add your handling code here:;
    try{
    int Empsalry=Integer.parseInt(Empsalary.getText());
    int Empsid=Integer.parseInt(Empid.getText());
    String Empnam=Empname.getText();
    String Empaddr=Empaddress.getText();
    String Empcit=Empcity.getText();
    Class.forName(“com.mysql.jdbc.Driver”);
    connection = DriverManager
    .getConnection(“jdbc:mysql://localhost:3306/empdet”, “root”, “”);

    stmt = connection.createStatement();
    //String str=();
    stmt.execute(“INSERT INTO EMPLOYEE VALUE”);
    }
    catch(Exception e){
    System.out.println(e.getMessage());
    }
    }

    private void EmpcityActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:

    }

    private void EmpnameActionPerformed(java.awt.event.ActionEvent evt) {

    }

    private void EmpidActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:

    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) throws ClassNotFoundException {

    /* Set the Nimbus look and feel */
    //
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
    * For details see https://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
    */
    try {
    for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
    if (“Nimbus”.equals(info.getName())) {
    javax.swing.UIManager.setLookAndFeel(info.getClassName());
    break;
    }
    }
    } catch (ClassNotFoundException ex) {
    java.util.logging.Logger.getLogger(Empdetail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
    java.util.logging.Logger.getLogger(Empdetail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
    java.util.logging.Logger.getLogger(Empdetail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
    java.util.logging.Logger.getLogger(Empdetail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //

    try {
    for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
    if (“Nimbus”.equals(info.getName())) {
    javax.swing.UIManager.setLookAndFeel(info.getClassName());
    break;
    }
    }
    } catch (ClassNotFoundException ex) {
    java.util.logging.Logger.getLogger(Empdetail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
    java.util.logging.Logger.getLogger(Empdetail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
    java.util.logging.Logger.getLogger(Empdetail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
    java.util.logging.Logger.getLogger(Empdetail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new Empdetail().setVisible(true);

    }
    });
    }
    // Variables declaration – do not modify
    private javax.swing.JTextArea Empaddress;
    private javax.swing.JTextField Empcity;
    private javax.swing.JTextField Empid;
    private javax.swing.JTextField Empname;
    private javax.swing.JTextField Empsalary;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration
    }

    Reply
  2. thank you
    I would like to refer to you for my class 12 project in the future…
    if thats Ok with you that is …

    Reply
  3. Just an addon,

    Difference between execute, executeQuery and executeUpdate :

    execute: Returns true if the first object that the query returns is a ResultSet object. Use this method if the query could return one or more ResultSet objects. Retrieve the ResultSet objects returned from the query by repeatedly calling Statement.getResultSet.

    executeQuery: Returns one ResultSet object.

    executeUpdate: Returns an integer representing the number of rows affected by the SQL statement. Use this method if you are using INSERT, DELETE, or UPDATE SQL statements.

    Source : https://docs.oracle.com/javase/tutorial/jdbc/basics/processingsqlstatements.html

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.