WebSQL自动增量不起作用

问题描述 投票:1回答:3

我正在将mysqlf引入WebSQL(是的,我知道它已被弃用,而我遇到了麻烦...

我通过Js创建数据库,如下所示:

function initDb(){

try {
    if (!window.openDatabase) {
        alert('Databases are not supported in this browser.');
    } else {

        var db = getDb();

        db.transaction(function (tx){
            tx.executeSql("CREATE TABLE IF NOT EXISTS tipofiesta (id INTEGER AUTO_INCREMENT, honor TEXT, descripcion_en TEXT, descripcion_es TEXT, descripcion_eu TEXT, PRIMARY KEY (id))", []);
            tx.executeSql("CREATE TABLE IF NOT EXISTS localizacion (id INTEGER AUTO_INCREMENT, latitud TEXT, longitud TEXT, PRIMARY KEY (id))", []);
            tx.executeSql("CREATE TABLE IF NOT EXISTS claseacto (id INTEGER AUTO_INCREMENT, nombre_en TEXT, nombre_es TEXT, nombre_eu TEXT, descripcion_en TEXT, descripcion_es TEXT, descripcion_eu TEXT, CONSTRAINT id_pk PRIMARY KEY (id))", []);
            tx.executeSql("CREATE TABLE IF NOT EXISTS AdministradorFiestas (id INTEGER AUTO_INCREMENT, nombreUsuario TEXT, pass TEXT, email TEXT, verificado BOOLEAN DEFAULT FALSE, CONSTRAINT id_pk PRIMARY KEY (id))", []);
            tx.executeSql("CREATE TABLE IF NOT EXISTS provincia (id INTEGER AUTO_INCREMENT, nombreCas varchar(25) DEFAULT 'nombre de provincia', nombreEus varchar(25) DEFAULT 'probintzia izena', id_localizacion INTEGER, CONSTRAINT id_pk PRIMARY KEY (id), FOREIGN KEY (id_localizacion) REFERENCES  localizacion(id))", []);
            tx.executeSql("CREATE TABLE IF NOT EXISTS pueblo (id INTEGER AUTO_INCREMENT, nombreCas TEXT, nombreEus TEXT, id_localizacion INTEGER, id_provincia INTEGER,  CONSTRAINT id_pk PRIMARY KEY (id), FOREIGN KEY (id_localizacion) REFERENCES localizacion(id), FOREIGN KEY (id_provincia) REFERENCES provincia(id))", []);
            tx.executeSql("CREATE TABLE IF NOT EXISTS fiesta (id INTEGER AUTO_INCREMENT, nombre TEXT, descripcion_eu TEXT, descripcion_en TEXT, descripcion_es TEXT, id_pueblo INTEGER, id_tipofiesta INTEGER, id_fechafiestaanyo INTEGER, CONSTRAINT id_pk PRIMARY KEY (id), FOREIGN KEY (id_pueblo) REFERENCES pueblo(id), FOREIGN KEY (id_tipofiesta) REFERENCES tipofiesta(id), FOREIGN KEY (id_fechafiestaanyo) REFERENCES fechafiestaanyo(id))", []);
            tx.executeSql("CREATE TABLE IF NOT EXISTS fechafiestaanyo (id INTEGER AUTO_INCREMENT, fechaInicio date, fechaFin date, id_fiesta INTEGER, CONSTRAINT id_pk PRIMARY KEY (id), FOREIGN KEY (id_fiesta) REFERENCES fiesta(id))", []);
            tx.executeSql("CREATE TABLE IF NOT EXISTS diafiesta (id INTEGER AUTO_INCREMENT, fecha date, nombre TEXT, descripcion_en TEXT, descripcion_es TEXT, descripcion_eu TEXT, id_fechafiestaanyo INTEGER, CONSTRAINT id_pk PRIMARY KEY (id), FOREIGN KEY (id_fechafiestaanyo) REFERENCES fechafiestaanyo(id))", []);
            tx.executeSql("CREATE TABLE IF NOT EXISTS acto (id INTEGER AUTO_INCREMENT, nombre_en TEXT, nombre_es TEXT, nombre_eu TEXT, descripcion_en TEXT, descripcion_es TEXT, descripcion_eu TEXT, horaInicio time, horaFinAprox time, id_localizacion INTEGER, id_diafiesta INTEGER, CONSTRAINT id_pk PRIMARY KEY (id), FOREIGN KEY (id_localizacion) REFERENCES localizacion(id), FOREIGN KEY (id_diafiesta) REFERENCES diafiesta(id))", []);
            tx.executeSql("CREATE TABLE IF NOT EXISTS actoclases (id INTEGER AUTO_INCREMENT, id_acto INTEGER, id_claseacto INTEGER, CONSTRAINT id_pk PRIMARY KEY (id), FOREIGN KEY (id_acto) REFERENCES acto(id), FOREIGN KEY (id_claseacto) REFERENCES claseacto(id))", []);
            tx.executeSql("CREATE TABLE IF NOT EXISTS AdministradorFiestasPueblo (id INTEGER AUTO_INCREMENT, idAdministradorFiestas INTEGER, idPueblo INTEGER, CONSTRAINT id_pk PRIMARY KEY (id), FOREIGN KEY (idAdministradorFiestas) REFERENCES AdministradorFiestas(id), FOREIGN KEY (idPueblo) REFERENCES pueblo(id))", []);
            tx.executeSql("CREATE TABLE IF NOT EXISTS tipofiestadefiesta (id INTEGER AUTO_INCREMENT, id_tipofiesta INTEGER, id_fiesta INTEGER, CONSTRAINT id_pk PRIMARY KEY (id), FOREIGN KEY (id_tipofiesta) REFERENCES tipofiesta(id), FOREIGN KEY (id_fiesta) REFERENCES fiesta(id))", []);
        });

    }
    return;
} catch(e) {

    if (e == 2) {
        // Version number mismatch.
        console.log("Invalid database version.");
    } else {
        console.log("Unknown error "+e+".");
    }
    return;
}

}

最大的问题是,每个表的“ id”列都不能与auto_increment子句一起使用...我可以使其工作吗?

否则,我正在创建一个函数,该函数告诉我表中可用的以下ID(以便添加数据等):

function nextIdInTableAvailable(tableName){

try {
    console.log("entramos");

    var idNotAvailable = false;
    var anId = 0;
    console.log("entramos al while...");

    var db = getDb();

    while(idNotAvailable==false){

        console.log("toca vuelta " + anId);
        var currentIdUsed = false;

        db.transaction(function (tx){

                tx.executeSql('SELECT * FROM ' + tableName + ' WHERE id=? ORDER BY id ASC', [anId], function (tx, results) {
                    console.log("hay resultados en la vuelta " + anId);
                    currentIdUsed = true;
                });

        });

        if(!currentIdUsed){
            idNotAvailable = true;
            console.log("vamos a salir en la vuelta " + anId);
        }else{
            anId = anId + 1;
            console.log("seguimos en vuelta siguiente: " + anId);
        }

    }


    console.log("El siguiente id disponible para la tabla '" + tableName + "' es: " + anId );

    return anId;

} catch(e) {

    if (e == 2) {
        // Version number mismatch.
        console.log("Invalid database version.");
    } else {
        console.log("Unknown error "+e+".");
    }

    return 0;

}

}

但是,还是一个问题:事务异步运行,因此不需要返回的值...

如果auto_increment无法正常工作,此功能有解决方案吗?

html5 web-sql
3个回答
0
投票

由于事务异步运行,因此无法以简单的方式返回值...

https://stackoverflow.com/a/12462907/828551 @apsillers有解决方案:回调。


0
投票

我使用ionic 4和SQLite。我想创建一个自动增量ID,但是每次在该表上插入数据时收到一条错误消息时,我都会创建一个。

这是我的表创建代码

this.database.executeSql('CREATE TABLE IF NOT EXISTS switch_types (switch_types_id INT(11) PRIMARY KEY ASC,image_path VARCHAR(150),status TINYINT(1),name VARCHAR(150),updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)', [])
  .then(() => {
    console.log('switch_types table created successfully');
    this.statusOfSwitch();
  })
  .catch(e => console.log('error on switch_types table creation' + JSON.stringify(e)));

这里是我的数据插入代码

addSwitchTypes(typeObj): Observable<any> {
const switchTypeData = [typeObj.image_path, typeObj.status, typeObj.name];
return new Observable((obs) => {
  this.database.executeSql('INSERT INTO switch_types (image_path, status, name) VALUES (?, ?, ?)', switchTypeData)
    .then(() => {
      console.log('switch type added successfully');
      obs.next(true);
      obs.complete();
    }).catch((error) => {
      console.log('switch type not added successfully', error);
      obs.error(error);
      obs.complete();
    });
});

}

我收到的错误消息

message: "sqlite3_step failure: NOT NULL constraint failed: switch_types.switch_types_id"

我已经尝试了几种方法,但是失败了。谁能帮我吗?我已经尝试了以下

  1. this.database.executeSql('如果不存在,则创建表switch_types(switch_types_id INT(11)NOT NULL主键自动递增,image_pathVARCHAR(150).......)
  2. this.database.executeSql('如果不存在则创建表switch_types(switch_types_id INT(11)PRIMARY KEY ASC,image_path VARCHAR(150).......)

this.database.executeSql('如果不存在则创建表switch_types(switch_types_id INT(11)PRIMARY KEY ASC,image_path VARCHAR(150).......)


-1
投票

对于'auto_increment',您可以尝试一下,它对我有用:

CREATE TABLE IF NOT EXISTS 'yourTableName' ('idPrimaryKey' INTEGER PRIMARY KEY ASC, 'column2' VARCHAR(45) NULL,'column3' TINYINT(1) NULL);
© www.soinside.com 2019 - 2024. All rights reserved.