Guilherme Oliveira
Guilherme Oliveira

Reputation: 11

Expo SQLite promisse rejection

I'm trying to make simple SQLite operations (such as selects and inserts), but it's not working at all.

Here is my function:

executarComando(strSql) {

    return new Promise((resolve, reject) => {
        db.transaction((tx) => {
            tx.executeSql(strSql, [], (tx, result) => {
                resolve(result);
            }, (err) => {
                reject(err);
            })
        },
        null,
        null)
    });
}

Where I call it:

    const strSelect = `
    SELECT true AS existe FROM tb0101_Usuarios WHERE
    nomeUSUARIO='${nomeUsuario}',
    cnpjUSUARIO='${cnpjUsuario}'
    `;
    const res = await executarComando(strSelect);

And the warning/error that it throw in my console log:

Possible Unhandled Promise Rejection (id: 0):
WebSQLTransaction {
  "_complete": true,
  "_error": null,
  "_running": false,
  "_runningTimeout": false,
  "_sqlQueue": Queue {
    "first": undefined,
    "last": undefined,
    "length": 0,
  },
  "_websqlDatabase": WebSQLDatabase {
    "_currentTask": null,
    "_db": SQLiteDatabase {
      "_closed": false,
      "_name": "TitaniumApp.db",
    },
    "_running": false,
    "_txnQueue": Queue {
      "first": undefined,
      "last": undefined,
      "length": 0,
    },
    "version": "1.0",
  },
}

Upvotes: 1

Views: 987

Answers (1)

Daniel Omiya
Daniel Omiya

Reputation: 21

Do something like the following.

executarComando(strSql, params = []) {
   return new Promise((resolve, reject) => {
       db.transaction((tx) => {
           tx.executeSql(strSql, params,
               (_, result) => resolve(result),
               (_, err) => reject(err));
       });
   });
}

It'll give you the actual error and not the transaction object.

Btw, it's worth mentioning that you should always protect your queries against sql injections. You can do it by simply replacing the directly concatenated values by ?, and passing them to the executeSql method:

const strSelect = `
    SELECT true AS existe FROM tb0101_Usuarios WHERE
    nomeUSUARIO=? AND
    cnpjUSUARIO=?
`;
const res = await executarComando(strSelect, [nomeUsuario, cnpjUsuario]);

Upvotes: 2

Related Questions