JDBC Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 2.11

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:

  • You don't have to provide values to columns that have default values defined.
  • You don't have to provide values to columns that allow null values.
  • You should not provide values to IDENTITY columns, mainly used as primary key columns.

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) 2007 by Dr. Herong Yang. 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(1269);
      ds.setDatabaseName("AdventureWorksLT");
      ds.setUser("Herong");
      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 confirms that insert statements was executed correctly:

C:\>javac -cp .;\local\lib\sqljdbc.jar SqlServerMultipleInserts.java

C:\>java -cp .;\local\lib\sqljdbc.jar SqlServerMultipleInserts
Number of rows inserted: 12
List of Profiles:
  1, Herong, null, 0.0, 1988-12-31, 2007-01-01 00:00:00.0
  2, Janet, Gates, 999.9890234375, 1984-10-13, 2007-01-01 00:00:00.0
  3, 1262, 70469, 696.89356875, 1988-12-31, 2007-01-01 00:00:00.0
  4, 135c, 3b291, 226.866060839844, 1988-12-31, 2007-01-01 00:00:00.0
  5, 1cc, 3f8a9, 517.886236875, 1988-12-31, 2007-01-01 00:00:00.0
  6, 248a, ade28, 634.84337890625, 1988-12-31, 2007-01-01 00:00:00.0
  7, 26, 39a85, 200.7675785, 1988-12-31, 2007-01-01 00:00:00.0
  8, 23fc, 63135, 332.93850800781, 1988-12-31, 2007-01-01 00:00:00.0
  9, 18c5, b7e7e, 742.11163359375, 1988-12-31, 2007-01-01 00:00:00.0
  10, 265, 39859, 179.678320898438, 1988-12-31, 2007-01-01 00:00:00.0
  11, f8e, bcce7, 726.69514296875, 1988-12-31, 2007-01-01 00:00:00.0
  12, 1785, 4be9, 749.823746875, 1988-12-31, 2007-01-01 00:00:00.0

Table of Contents

 About This Book

 JDBC (Java Database Connectivity) Introduction

 Downloading and Installing JDK - Java SE

 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 - sqljdbc.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

 References

 PDF Printing Version

Dr. Herong Yang, updated in 2007
Inserting Rows to the Test Table