"INSERT INTO" Statements

Describes how to insert data rows with INSERT INTO statements.

INSERT statements are used very often by database applications to insert data rows into tables. The syntax of INSERT statements is very simple. You need to provide a list of column names and a list of values for those columns. There are a couple of simple rules about INSERT statements:

INSERT statements should be executed with the executeUpdate() method. Here is a simple program that insert some rows into my table Profile:

/* MySqlMultipleInserts.java
 * Copyright (c) 2005 HerongYang.com. All Rights Reserved.
 */
import java.util.*;
import java.sql.*;
public class MySqlMultipleInserts {
  public static void main(String [] args) {
    Connection con = null;
    try {

// Setting up the DataSource object
      // For MySQL Connector/J 5.1.38
      // com.mysql.jdbc.jdbc2.optional.MysqlDataSource ds
      //   = new com.mysql.jdbc.jdbc2.optional.MysqlDataSource();

      // For MySQL Connector/J 8.0.17
      com.mysql.cj.jdbc.MysqlDataSource ds
        = new com.mysql.cj.jdbc.MysqlDataSource();
      ds.setServerName("localhost");
      ds.setPortNumber(3306);
      ds.setDatabaseName("test");
      ds.setUser("root");
      ds.setPassword("TopSecret");

// Getting a connection object and statement object
      con = ds.getConnection();
      Statement sta = con.createStatement();
      int count = 0;

// insert a single row using default values
      count += sta.executeUpdate(
        "INSERT INTO Profile"
        + " (FirstName)"
        + " VALUES ('Herong')");

// insert a single row using provided values
      count += sta.executeUpdate(
        "INSERT INTO Profile"
        + " (FirstName, LastName, Point, BirthDate)"
        + " VALUES ('Janet', 'Gates', 999.99, '1984-10-13')");

// insert rows with loop with random values
      Random r = new Random();
      for (int i=0; i<10; i++) {
        Float points = 1000*r.nextFloat();
        String firstName = Integer.toHexString(r.nextInt(9999));
        String lastName = Integer.toHexString(r.nextInt(999999));
        count += sta.executeUpdate(
          "INSERT INTO Profile"
          + " (FirstName, LastName, Point)"
          + " VALUES ('"+firstName+"', '"+lastName+"', "+points+")");
      }

// How many rows were inserted
      System.out.println("Number of rows inserted: "+count);

// Checking inserted rows
      ResultSet res = sta.executeQuery(
        "SELECT * FROM Profile");
      System.out.println("List of Profiles: ");
      while (res.next()) {
         System.out.println(
           "  "+res.getInt("ID")
           + ", "+res.getString("FirstName")
           + ", "+res.getString("LastName")
           + ", "+res.getDouble("Point")
           + ", "+res.getDate("BirthDate")
           + ", "+res.getTimestamp("ModTime"));
      }
      res.close();

      sta.close();
      con.close();
    } catch (Exception e) {
      System.err.println("Exception: "+e.getMessage());
    }
  }
}

Notice that Random class was used to generate some random strings and numbers.

The output on my MySQL 8.0 server confirms that the insert statement was executed correctly:

herong> java -cp .;\local\lib\mysql-connector-java-8.0.17.jar
  MySqlMultipleInserts

Number of rows inserted: 12
List of Profiles:
  1, Herong, null, 0.0, 1988-12-31, 2017-01-01 00:00:00.0
  2, Janet, Gates, 999.99, 1984-10-13, 2017-01-01 00:00:00.0
  3, d79, da84d, 638.8607, 1988-12-31, 2017-01-01 00:00:00.0
  4, 189c, 4335d, 606.4067, 1988-12-31, 2017-01-01 00:00:00.0
  5, 483, 21b72, 805.1093, 1988-12-31, 2017-01-01 00:00:00.0
  6, 13c0, d8df0, 470.5137, 1988-12-31, 2017-01-01 00:00:00.0
  7, 1b33, 500c3, 639.86914, 1988-12-31, 2017-01-01 00:00:00.0
  8, c6b, 5eead, 638.0474, 1988-12-31, 2017-01-01 00:00:00.0
  9, 36, 581b9, 81.03996, 1988-12-31, 2017-01-01 00:00:00.0
  10, 1383, 9318, 33.663452, 1988-12-31, 2017-01-01 00:00:00.0
  11, 1e3c, 761e2, 657.63495, 1988-12-31, 2017-01-01 00:00:00.0
  12, 1a7f, 45d40, 569.61865, 1988-12-31, 2017-01-01 00:00:00.0

However, the default value, 2016-12-31 23:59:59.999, of the ModTime TIMESTAMP column was being returned as 2017-01-01 00:00:00.0. My guess is that MySQL server does not really support millisecond in TIMESTAMP. The 999 millisecond was rounded up to an extra second, resulting 2017-01-01 00:00:00.

As a comparison, here is the output on MySQL 5.0 server, which truncated the 999 millisecond to 0:

Number of rows inserted: 12
List of Profiles:
  1, Herong, null, 0.0, 1988-12-31, 2016-12-31 23:59:59.0
  2, Janet, Gates, 999.99, 1984-10-13, 2016-12-31 23:59:59.0
  3, 1093, 9c94a, 694.96106, 1988-12-31, 2016-12-31 23:59:59.0
  4, 2556, 7c501, 654.16656, 1988-12-31, 2016-12-31 23:59:59.0
  5, 2514, ee0b8, 134.08804, 1988-12-31, 2016-12-31 23:59:59.0
  6, 11b1, 91714, 614.86383, 1988-12-31, 2016-12-31 23:59:59.0
  7, 9ac, 608cc, 941.5479, 1988-12-31, 2016-12-31 23:59:59.0
  8, 1b37, ec682, 290.13306, 1988-12-31, 2016-12-31 23:59:59.0
  9, 16a8, dabd2, 251.7339, 1988-12-31, 2016-12-31 23:59:59.0
  10, eec, 7d583, 674.99347, 1988-12-31, 2016-12-31 23:59:59.0
  11, ab1, c465f, 566.3607, 1988-12-31, 2016-12-31 23:59:59.0
  12, 1914, 4f9a4, 366.74844, 1988-12-31, 2016-12-31 23:59:59.0

Table of Contents

 About This Book

 Introduction of SQL

 MySQL Introduction and Installation

 Introduction of MySQL Programs

 PHP Programs and MySQL Server

 Perl Programs and MySQL Servers

Java Programs and MySQL Servers

 MySQL Connector/J - Download and Installation

 Loading JDBC Driver Class - com.mysql.cj.jdbc.Driver

 JDBC Driver Connection URL

 Connection URL Tests on Older MySQL Connector/J

 Creating Connections with DataSource Class

 Getting Driver and Server Information

 Creating Tables with AUTO_INCREMENT Columns

"INSERT INTO" Statements

 Datatypes and Data Literals

 Operations and Expressions

 Character Strings and Bit Strings

 Commonly Used Functions

 Table Column Types for Different Types of Values

 Using DDL to Create Tables and Indexes

 Using DML to Insert, Update and Delete Records

 Using SELECT to Query Database

 Window Functions for Statistical Analysis

 Use Index for Better Performance

 Transaction Management and Isolation Levels

 Locks Used in MySQL

 Defining and Calling Stored Procedures

 Variables, Loops and Cursors Used in Stored Procedures

 System, User-Defined and Stored Procedure Variables

 MySQL Server Administration

 Storage Engines in MySQL Server

 InnoDB Storage Engine - Primary and Secondary Indexes

 Performance Tuning and Optimization

 Bulk Changes on Large Tables

 MySQL Server on macOS

 Installing MySQL Server on Linux

 Connection, Performance and Second Instance on Linux

 Archived Tutorials

 References

 Full Version in PDF/EPUB