I want to use Web sql but I’m not able to create table or insert information in it

Asked

Viewed 263 times

1

let db = openDatabase('produto_teste','1.0','banco de dados para cadastro do produto',2*1024*1024);
db.transaction(function(tx){
  tx.executeSql('CREATE TABLE IF NOT referencia(\
    id INTEGER NOT NULL AUTOINCREMENT,\
    nome VARCHAR NOT NULL,\
    marca VARCHAR NOT NULL,\
    categoria VARCHAR NOT NULL,\
    template VARCHAR NOT NULL,\
    grade INTEGER NOT NULL\
  );',[[]],null,null);
})

This is my connection code, it creates the bank but it’s not creating the table, what can it be? The way I’m doing this wrong? When I open the developer tools and go to applications I find the database I created but there are no tables

1 answer

3


When you’re working with WebSql and an error occurs, add a callback error return when calling the transaction.executeSql.:

let db = openDatabase('produto_teste','1.0','banco de dados para cadastro do produto',2*1024*1024);
db.transaction(function(tx){
  tx.executeSql('CREATE TABLE IF NOT referencia(\
    id INTEGER NOT NULL AUTOINCREMENT,\
    nome VARCHAR NOT NULL,\
    marca VARCHAR NOT NULL,\
    categoria VARCHAR NOT NULL,\
    template VARCHAR NOT NULL,\
    grade INTEGER NOT NULL\
  );',[[]],null, function (t, e) { console.error(e); });
})

In doing this, I would have seen the following

SQLError {code: 5, message: "could not prepare statement (1 near "referencia": syntax error)"}
SQLError {code: 5, message: "could not prepare statement (1 near "AUTOINCREMENT": syntax error)"}
SQLError {code: 5, message: "number of '?'s in statement string does not match argument count"}

So if we solve these problems, we will have the following script.:

let db = openDatabase('produto_teste','1.0','banco de dados para cadastro do produto',2*1024*1024);
db.transaction(function(tx){
  tx.executeSql('CREATE TABLE IF NOT EXISTS referencia(\
    id INTEGER PRIMARY KEY AUTOINCREMENT,\
    nome VARCHAR NOT NULL,\
    marca VARCHAR NOT NULL,\
    categoria VARCHAR NOT NULL,\
    template VARCHAR NOT NULL,\
    grade INTEGER NOT NULL\
  );',[], null, null);
})

But try to look at a detail, the WebSQL does not have a good support CrossBrowser, your code won’t work on IE and Firefox.

I advise you to use the LocalDB.js in place of WebSQL

  • Buddy Indexeddb you think a good option?

  • Thank you very much for your help!

  • @Indexeddb will also suffer with the compatibility problem, I advise you to use some micro library that abstracts this, as Localdb quoted in the answer, it will use Websql if available, if not Indexeddb, finally will use localStorage or sessionStorage

  • Blz. Thanks for the tip.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.