SirGoose SirGoose - 3 months ago 6
Java Question

How to find what id to use next in sqlite3 and java

I'm currently using java and jdbc to work with sqlite. When inserting a new object into a database, how am I supposed to know which id to use or how to generate it?

Here's my code I'm using:

private void insertIntoTable() {
Connection c = null;
Statement stmt = null;

try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:src/test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");

stmt = c.createStatement();
String sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" +
"VALUES (2 , 'Brian Brianson', 32, 'California', 60000.00);";
stmt.executeUpdate(sql);

stmt.close();
c.commit();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}


When I'm inserting new items, how should I find out which id I should be using to insert into the database?

Answer

You should make that ID column auto increment, and then just insert NULL values for it. SQLite should automatically assign an ID value for you. That is, use this code:

String sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" +
             "VALUES (null, 'Brian Brianson', 32, 'California', 60000.00);";
stmt.executeUpdate(sql);
Comments