创建表的代码
if (!this.isOpen) {
this.storage = new SQLite();
this.storage.create({ name: "form.db", location: "default" }).then((db: SQLiteObject) => {
this.db = db;
db.executeSql("CREATE TABLE IF NOT EXISTS formstable (formId VARCHAR PRIMARY KEY, clientId VARCHAR, formsdata VARCHAR)", []);
console.log("table created successfully");
this.isOpen = true;
}).catch((error) => {
console.log(error);
})
}
这是我用来将数据插入SQLLite的函数
Savedata(formId:string, clientId:string,formsdata:string){
return new Promise ((resolve, reject) => {
let sql = "INSERT OR REPLACE INTO formstable (formId, clientId,formsdata) VALUES (?,?,?)";
this.db.executeSql(sql, [formId, clientId,formsdata]).then((data) =>{
resolve(data);
console.log(data);
console.log("data inserted successfully")
}, (error) => {
reject(error);
});
});
}
函数从SQLLite获取值
GetAlldata(){
return new Promise ((resolve, reject) => {
this.db.executeSql("SELECT * FROM formstable", []).then((data) => {
let arrayUsers = [];
if (data.rows.length > 0){
for (var i = 0; i < data.rows.length; i++) {
arrayUsers.push({
formId: data.rows.item(i).formId,
clientId: data.rows.item(i).clientId,
formsdata: JSON.parse(data.rows.item(i).formsdata)
});
}
}
resolve(arrayUsers);
}, (error) => {
reject(error);
})
})
}
我在表中的值“formsdata”是一个json,它被转换成字符串并保存到数据库中,在获取时解析成json。每次我调用函数“savadata()”时,三个值(formid,clientid,formsdata)被一次又一次地插入。所以如何避免重复的值,我尝试了“replace”关键字,但没有成功
1条答案
按热度按时间daupos2t1#
你必须把formid作为主键。在表模式中,将必需的字段更改为主键,以便替换可以工作。