When creating a table in SQLite, the column you want to use as the primary key (id
in this case) must have been created with exactly the keywords INTEGER PRIMARY KEY
in order for its behavior to become SQLite's lightweight version of auto-increment. This is what allows you to add a row without supplying the column's value (SQLite will fill it in for you). INT PRIMARY KEY
will not do it, nor will UNSIGNED INTEGER PRIMARY KEY
, nor will any other variation. Try recreating the table with INTEGER PRIMARY KEY
as the type for id
(you can also add the NOT NULL
constraint).
You can optionally add the keyword AUTOINCREMENT
to the definition of id
(that is, use INTEGER PRIMARY KEY AUTOINCREMENT
). This will force SQLite to not reuse IDs of previously deleted rows when adding new rows, but this is slower and takes up more memory and disk space.
Here's an example of how to create your table in SQLite so that you don't have to fill in id
when you insert a row:
CREATE TABLE stock(id INTEGER PRIMARY KEY, pname TEXT, mrp TEXT);
P.S. - Since this special functionality of INTEGER PRIMARY KEY
works by creating an alias from id
to ROWID
, you should not also use the WITHOUT ROWID
keywords when creating the table.
P.P.S. - You are not closing the SQL connections you created in the code above (there are other major issues I'm ignoring, but that one is the most important). You need to do so in a finally
clause to ensure the connection is closed even in the event of an exception:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Connection con = null;
try {
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:qmb.db");
String query="INSERT INTO stock(pname,mrp) VALUES('"+jTextField2.getText()+"','"+jTextField5.getText()+"');";
executeSQlQuery(query, "Inserted"); // TODO add your handling code here:
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(UpdateStock.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException ex) {
Logger.getLogger(UpdateStock.class.getName()).log(Level.WARNING, "can't close SQL connection!" , ex);
}
}
}
}