3

I'm working off of an example to learn node.js/sqlite3, shown here: https://github.com/mapbox/node-sqlite3/blob/master/examples/simple-chaining.js

In the example, the table only has only column, and I wanted to extend it so the table has three columns--for username, password, and login count.

So I changed the original code, here:

function createTable() {
    console.log("createTable lorem");
    db.run("CREATE TABLE IF NOT EXISTS lorem (info TEXT)", insertRows);
}

to this:

function createTable() {
    console.log("createTable lorem");
    db.run("CREATE TABLE IF NOT EXISTS lorem (info TEXT, name TEXT)", insertRows);
}

but when trying to fill it with values, I get an error:

~:dev$ node chaining.js 
createDb chain
createTable lorem
insertRows Ipsum i

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: SQLITE_ERROR: table lorem has 1 columns but 2 values were supplied
~:dev$ 

Am I creating the table incorrectly? I referred to the SQLITE api, as well as W3schools, but none seem to indicate that I'm doing it incorrectly.

I've provided my code below:

/**
 * Shows how to use chaining rather than the `serialize` method.
 */
"use strict";

var sqlite3 = require('sqlite3').verbose();
var db;

function createDb() {
    console.log("createDb chain");
    db = new sqlite3.Database('chain.sqlite3', createTable);
}


function createTable() {
    console.log("createTable lorem");
    db.run("CREATE TABLE lorem (info TEXT, name TEXT)", insertRows);
}

function insertRows() {
    console.log("insertRows Ipsum i");
    var stmt = db.prepare("INSERT INTO lorem VALUES (?, ?)");

    for (var i = 0; i < 10; i++) {
        stmt.run("Ipsum " + i, "lala " + i);
    }

    stmt.finalize(readAllRows);
}

function readAllRows() {
    console.log("readAllRows lorem");
    db.all("SELECT rowid AS id, info, name FROM lorem", function(err, rows) {
        rows.forEach(function (row) {
            console.log(row.id + ": " + row.info + ": " + row.name);
        });
        closeDb();
    });
}

function closeDb() {
    console.log("closeDb");
    db.close();
}

function runChainExample() {
    createDb();
}

runChainExample();

1 Answer 1

3

It sounds like the table already exists, possibly from a previous run of your script. The quickest way to test this would be to just change the name of the sqlite database you are creating.

db = new sqlite3.Database('chain.sqlite3', createTable);

to

db = new sqlite3.Database('chain2.sqlite3', createTable);

If that works, then that's the issue. You could also modify your script to first DROP the table before creating it if it exists.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.