Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting Id field autoincrement with sqlite3 and node.js

Tags:

node.js

sqlite

I am trying to insert into sqlite3 with node.js. I need a unique id field however I would like it to auto generate so I do not have to insert it when inserting to the table. I am getting connected and creating the table ok however then when I am inserting it is expecting me to supply an id field. Here is the code so far:

var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('database/setup.db');


db.serialize(function() {
db.run("CREATE TABLE items (id INTEGER PRIMARY KEY, title TEXT, images TEXT, bid INTEGER, currentBidder TEXT)");

var stmt = db.prepare("INSERT INTO items VALUES(?,?,?,?)");
stmt.run('Title test 123', 'http://testshjshs', 100, 'shane'); 
stmt.finalize();

db.each("SELECT rowid, title FROM test", function(err, row) {
  console.log(row.rowid + ": " + row.title);
});

});

db.close();

This is returning the following error.

Error: SQLITE_ERROR: table items has 5 columns but 4 values were supplied

I understand why it is returning the following error but how do I set it so it inserts auto inserts the field or is this not possible? Thanks

like image 435
Shane_S Avatar asked Dec 10 '25 14:12

Shane_S


2 Answers

The table has been declared with five columns, so when you give only four values to the INSERT, it doesn't know which column to omit.

Either explicitly say into which columns you want to insert:

INSERT INTO items(title,images,bid,currentBidder) VALUES(?,?,?,?)

Or give a value for all five columns (NULL means autoincrement):

INSERT INTO items VALUES(NULL,?,?,?,?)
like image 96
CL. Avatar answered Dec 13 '25 07:12

CL.


If you want an auto incrementing field in your table, leave out the WITHOUT ROWID command when creating your table, and SQLite will create an automatic index for you, under the row name rowid

http://www.sqlitetutorial.net/sqlite-autoincrement/

like image 22
Abraham Brookes Avatar answered Dec 13 '25 07:12

Abraham Brookes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!