Inserting Rows to the Test Table

This section describes how to insert rows to the test table with an IDENTITY column.

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 inserts some rows into my table Profile:

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

// Setting up the DataSource object
      com.microsoft.sqlserver.jdbc.SQLServerDataSource ds 
        = new com.microsoft.sqlserver.jdbc.SQLServerDataSource();
      ds.setServerName("localhost");
//      ds.setPortNumber(60782);
      ds.setInstanceName("SQLEXPRESS");
      ds.setDatabaseName("AdventureWorks2014");
      ds.setUser("Herong");
      ds.setPassword("T0pSecret");
      con = ds.getConnection();

// 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) {
      e.printStackTrace();
    }
  }
}

Notice that Random class was used to generate some random strings and numbers. The output confirms that insert statements was executed correctly:

C:\herong>\Progra~1\java\jdk1.8.0_45\bin\javac
   -cp .;\local\lib\sqljdbc42.jar SqlServerMultipleInserts.java

C:\herong>\Progra~1\java\jdk1.8.0_45\bin\java 
   -cp .;\local\lib\sqljdbc42.jar SqlServerMultipleInserts

Number of rows inserted: 12
List of Profiles:
  1, Herong, null, 0.0, 1999-12-31, 2015-01-01 00:00:00.0
  2, Janet, Gates, 999.989990234375, 1984-10-13, 2015-01-01 00:00:00.0
  3, 169a, 662ef, 16.97826385498047, 1999-12-31, 2015-01-01 00:00:00.0
  4, 37d, f62e, 535.648193359375, 1999-12-31, 2015-01-01 00:00:00.0
  5, 14c, 7e51d, 791.2808227539062, 1999-12-31, 2015-01-01 00:00:00.0
  6, 216e, 176a5, 901.8399658203125, 1999-12-31, 2015-01-01 00:00:00.0
  7, 1a9d, dfbfa, 758.2083740234375, 1999-12-31, 2015-01-01 00:00:00.0
  8, 1b81, 90f4d, 277.23638916015625, 1999-12-31, 2015-01-01 00:00:00.0
  9, 1e20, 337be, 728.1421508789062, 1999-12-31, 2015-01-01 00:00:00.0
  10, 17c2, 5b7bd, 959.3673706054688, 1999-12-31, 2015-01-01 00:00:00.0
  11, 89, 5c364, 984.4622192382812, 1999-12-31, 2015-01-01 00:00:00.0
  12, 653, c89d4, 464.9222412109375, 1999-12-31, 2015-01-01 00:00:00.0

Last update: 2015.

Table of Contents

 About This Book

 JDBC (Java Database Connectivity) Introduction

 JDK (Java SE) Installation

 Installing and Running Java DB - Derby

 Derby (Java DB) JDBC Driver

 Derby (Java DB) JDBC DataSource Objects

 Java DB (Derby) - DML Statements

 Java DB (Derby) - ResultSet Objects of Queries

 Java DB (Derby) - PreparedStatement

 MySQL Installation on Windows

 MySQL JDBC Driver (MySQL Connector/J)

 MySQL - PreparedStatement

 MySQL - Reference Implementation of JdbcRowSet

 MySQL - JBDC CallableStatement

 MySQL CLOB (Character Large Object) - TEXT

 MySQL BLOB (Binary Large Object) - BLOB

 Oracle Express Edition Installation on Windows

 Oracle JDBC Drivers

 Oracle - Reference Implementation of JdbcRowSet

 Oracle - PreparedStatement

 Oracle - JBDC CallableStatement

 Oracle CLOB (Character Large Object) - TEXT

 Oracle BLOB (Binary Large Object) - BLOB

 Microsoft SQL Server 2005 Express Edition

 Microsoft JDBC Driver for SQL Server - sqljdbc42.jar

 Microsoft JDBC Driver - Query Statements and Result Sets

 Microsoft JDBC Driver - DatabaseMetaData Object

 Microsoft JDBC Driver - DDL Statements

 Microsoft JDBC Driver - DML Statements

SQL Server - PreparedStatement

 Create a New User in SQL Server

 Creating a Table with an IDENTITY Column

Inserting Rows to the Test Table

 PreparedStatement Overview

 PreparedStatement with Parameters

 PreparedStatement in Batch Mode

 Performance of Inserting Rows with a PreparedStatement

 Performance of Inserting Rows with a Regular Statement

 Performance of Inserting Rows with a ResultSet

 SQL Server CLOB (Character Large Object) - TEXT

 SQL Server BLOB (Binary Large Object) - BLOB

 JDBC-ODBC Bridge Driver - sun.jdbc.odbc.JdbcOdbcDriver

 JDBC-ODBC Bridge Driver - Flat Text Files

 JDBC-ODBC Bridge Driver - MS Access

 JDBC-ODBC Bridge Driver - MS SQL Server

 Summary of JDBC Drivers and Database Servers

 Additional Tutorial Notes to Be Added

 Outdated Tutorials

 References

 PDF Printing Version