This section describes what will happen if you try to insert rows with values for INDENTITY columns.
An INDENTITY column is a special column in a table that defined to have it value automatically added with
a sequence number generator. An INDENTITY column is normal used for the primary key column in a table.
For example, the UserID column in the Profile table created in a previous tutorial is an INDENTITY column.
If you try to add values to an INDENTITY column in INSERT statements, you will get an error as shown
in the sample program below:
/**
* InsertIdentity.java
* Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
*/
import java.sql.*;
public class InsertIdentity {
public static void main(String [] args) {
Connection con = null;
try {
Class.forName(
"com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(
"jdbc:sqlserver://localhost:1269;"
+ "user=sa;password=HerongYang;"
+ "database=AdventureWorksLT");
Statement sta = con.createStatement();
// insert a single row
int count = sta.executeUpdate(
"INSERT INTO Herong.Profile"
+ " (UserID, FirstName, LastName, LastAccessDate)"
+ " VALUES (1001, 'Herong', 'Yang', '2007-04-01')");
System.out.println("Number of rows inserted: "+count);
sta.close();
con.close();
} catch (java.lang.ClassNotFoundException e) {
System.err.println("ClassNotFoundException: "
+e.getMessage());
} catch (SQLException e) {
System.err.println("SQLException: "
+e.getMessage());
}
}
}
Here is the error message from this program:
SQLException: Cannot insert explicit value for identity column
in table 'Profile' when IDENTITY_INSERT is set to OFF.