简体   繁体   English

PhoneGap存储,将变量传递给db.transaction,SQL Lite

[英]PhoneGap storage, Passing Variables to db.transaction, SQL Lite

I'm working with the PhoneGap Open Database API. 我正在使用PhoneGap开放数据库API。 According to this documentation values should be inserted into an existing table using the follow code 根据此文档,应使用以下代码将值插入现有表中

function populateDB(tx) {
     tx.executeSql('DROP TABLE IF EXISTS DEMO');
     tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)');
     tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "First row")');
     tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")');
}

function errorCB(tx, err) {
    alert("Error processing SQL: "+err);
}

function successCB() {
    alert("success!");
}

  var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
  db.transaction(populateDB, errorCB, successCB);

This works fine but now I'm trying to pass a variable to the populateDB function. 这工作正常,但现在我正尝试将变量传递给populateDB函数。 When I try the code below 当我尝试下面的代码

  var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
  db.transaction(populateDB("test variable"), errorCB, successCB);

the "test variable" string goes through but tx is undefined. “测试变量”字符串通过,但未定义tx。 Does anyone know how to do this? 有谁知道如何做到这一点?

I think the only way you could do this would be write a function that returns a function that makes use of the passed in value. 我认为您可以执行此操作的唯一方法是编写一个函数,该函数返回一个使用传入值的函数。 Something along the lines of : 类似于以下内容:

function makeMyDB(x) {
    var result = function() {
     tx.executeSql('DROP TABLE IF EXISTS DEMO');
     tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)');
     tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "'+x+'")');
    }
   return result;
} 

You could then try passing makeMyDB(x) as the first argument. 然后,您可以尝试将makeMyDB(x)作为第一个参数传递。

If anyone else is still looking for a solution to this problem, I have a little solution for passing variable without changing or loosing the tx , you just have to write this for example: 如果其他任何人仍在寻找解决此问题的方法,那么我有一点办法可以通过传递变量而不更改或丢失tx ,您只需编写以下示例:

var myvar = 1; //an int or something else
db.transaction(function(tx){
    selectQueryDB(tx,myvar);
    },errorCB);



function selectQueryDB(tx,myvar){
    tx.executeSql('SELECT * FROM mytable WHERE myparam='+myvar, [], renderList, errorCB);

}

function errorCB(err){
    alert("Error Processing SQL: "+ err.code );
}
function renderList(tx,results){
enter code here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM