我正在开发一个phonegap应用程序,我希望它能使用sqlite。我按照教程进行了操作,但它没有工作。
这是我的代码:
<script type="text/javascript">
//add listener when device ready
document.addEventListener("deviceready", onDeviceReady, false);
var db;
var dbex; // Hope it allows me to work with DB outside populateDB function
//function will be called when device ready
function onDeviceReady(){
db = window.openDatabase("Test_DB", "1.0", "My DB for Test", 200000); //will create database Test_DB or open it
db.transaction(populateDB, errorCB, successCB);
}
//create table and insert some record
function populateDB(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS Usuario (id INTEGER PRIMARY KEY AUTOINCREMENT, Nombre TEXT NOT NULL, Edad INTEGER NOT NULL, Email TEXT, Localidad TEXT, Pais TEXT NOT NULL)');
tx.executeSql('CREATE TABLE IF NOT EXISTS Datos (id INTEGER PRIMARY KEY AUTOINCREMENT, text_one TEXT, text_two TEXT, text_emg TEXT, color TEXT)');
for (var i = 0; i > 4; i++) {
tx.executeSql('INSERT INTO Datos(text_one,text_two,text_emg, color) VALUES ("rouge", "vermelho", "-", "red")');
}; //congruente
dbex = tx;
}
//function will be called when an error occurred
function errorCB(err) {
$("#siguiente").html('error');
alert("Error processing SQL: "+err.code);
}
//function will be called when process succeed
function successCB() {
$("#siguiente").html('success');
alert("success!");
db.transaction(queryDB,errorCB);
}
//select all from Usuario
function queryDB(tx){
tx.executeSql('SELECT * FROM Usuario',[],querySuccess,errorCB);
}
var pinchado = document.getElementById("registro");
pinchado.disabled = true;
pinchado.onclick = function(){
var nombre = document.getElementById("nombre");
var edad = document.getElementById("edad");
var email = document.getElementById("email");
var localidad = document.getElementById("localidad");
var pais = document.getElementById("pais");
dbex.executeSql('INSERT INTO Usuario(Nombre,Edad,Email,Localidad,Pais) VALUES (nombre.value,edad.value,email.value,localidad.value,pais.value)');
function querySuccess(tx,result){
console.log("querySuccess")
$("#siguiente").html('result');
}
}
function doCheck(){
var allFilled = true;
var inputs = document.getElementsByTagName('input');
for(var i=0; i<inputs.length; i++){
if(inputs[i].value == ''){
allFilled = false;
break;
}
}
pinchado.disabled = !allFilled;
}
window.onload = function(){
var inputs = document.getElementsByTagName('input');
for(var i=0; i<inputs.length; i++){
if(inputs[i].type == "text"){
inputs[i].onkeyup = doCheck;
inputs[i].onblur = doCheck;
}
}
};
但是我收到了这个错误:
Uncaught TypeError: Cannot call method 'executeSql' of undefined index.html:134
pinchado.onclick
有什么想法吗?
答案 0 :(得分:1)
尝试在db=window.openDatabase()
内移动onDeviceReady()
,以便正确初始化变量db
。
function onDeviceReady() {
db=window.openDatabase("Trial_DB", "1.0", "My DB for Test", 200000);
db.transaction(populateDB, errorCB, successCB);
}