viana
viana

Reputation: 515

Muiltples insert using executeSql

I need to do multiple inserts and I do not know what's wrong. See:

 db.openDatabase({
      name: "data.db",
      location: "default"
    }).then(() => {
      db.executeSql(
        +"INSERT INTO check_item (name) VALUES ('Pneus - calibragem'); "
        +"INSERT INTO check_item (name) VALUES ('Pneus – banda de rodagem'); "
        +"INSERT INTO check_item (name) VALUES ('Nivel do oleo'); "
        +"INSERT INTO check_item (name) VALUES ('Luzes dianteiras'); "
        +"INSERT INTO check_item (name) VALUES ('Luzes traseiras'); "
        +"INSERT INTO check_item (name) VALUES ('Triangulo de sinalizacao'); "
        +"INSERT INTO check_item (name) VALUES ('Chave de roda'); "
        +"INSERT INTO check_item (name) VALUES ('Documentacao do veiculo'); ", {}).then((data) => {
          console.log("TABLE CREATED: ", data);
        }, (error) => {
          console.error("Unable to execute sql teste", error);

        })
    }, (error) => {
      console.error("Unable to open database", error);
    });

How can I fix this?

Upvotes: 1

Views: 1027

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521579

You are currently trying to execute multiple insertion statements within a single call to executeSql(). The syntax for inserting multiple records in a single statement is:

INSERT INTO check_item (name)
VALUES ('Pneus - calibragem'),
       ('Pneus – banda de rodagem'),
       ('Nivel do oleo'),
       ...
       ('Documentacao do veiculo');

If you want to prevent the possibility of inserting a name which already exists, the easiest way to do this is perhaps to add a unique constraint on the name column. While it isn't possible to do this in SQLite without recreating the table, we can add a unique index to get the same effect:

CREATE UNIQUE INDEX name_index ON check_item (name);

Further reading: How to add unique constraint in already made table in sqlite ios?

Upvotes: 3

user7580681
user7580681

Reputation:

INSERT INTO tbl_name (a,b,c) VALUES (1,2,3), (4,5,6), (7,8,9);

Upvotes: 1

Related Questions