简体   繁体   English

如何在事务回调函数中传递参数

[英]how can I pass argument in transaction callback function

From a tutorial code like this 从像这样的教程代码

function queryDB(tx) {
    tx.executeSql('SELECT * FROM DEMO', [], querySuccess, errorCB);
}

function querySuccess(tx, results) {

}

function errorCB(err) {
    alert("Error processing SQL: "+err.code);
}

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

in db.transaction i want to pass a variable as argument to queryDB function, so the code which i think of should looks like 在db.transaction中我想将一个变量作为参数传递给queryDB函数,所以我想到的代码应该是这样的

db.transaction(queryDB(id), errorCB);

How I can actually implement this ? 我怎么能实际实现这个? Or its simply gonna work like this and my id will be passed and get in tx ? 或者它只是像这样工作,我的身份证将被传递并进入tx?

I like to keep things very simple so I use a limited number of functions when handling storage on phonegap applications that can receive parameters. 我喜欢保持简单,所以在处理可以接收参数的phonegap应用程序上的存储时,我使用有限数量的功能。 A lot of the examples I have seen have calls to many sub functions and for me, this is a nightmare when it comes to debugging. 我见过的很多例子都调用了很多子函数,对我来说,这在调试方面是个噩梦。

I was caught out an a number of issues around Web SQL but reading the specs really, really helped clarify what I could and couldn't do. 我遇到了围绕Web SQL的一些问题但是真正阅读这些规范,确实有助于澄清我能做什么和不能做什么。 ( http://www.w3.org/TR/webdatabase/ ) http://www.w3.org/TR/webdatabase/

Look at this simple code for an insert function: 查看插入函数的这个简单代码:

function dbInsert(param1, param2, dbObj) {
    val1 = param1;
    val2 = param2;
    val3 = String(dbObj.item2);

    var sqlTxt = "INSERT INTO demo (geo1, geo2, geo3) VALUES (?, ?, ?)";
    db.transaction(function(tx) {tx.executeSql(sqlTxt,[val1,val2,val3])}, errorCB, successCB);
    }

Lets just to walk through it. 让我们走过它。 Obviously a standard function which receives parameters which can be anything, in this case an object as well a strings. 显然是一个标准函数,它接收可以是任何东西的参数,在这种情况下是一个对象以及一个字符串。

sqlTxt is where the fun begins. sqlTxt是有趣的开始。 Write this as you would normally write an insert statement, but where you would normally have the data to be inserted/selected etc in VALUES use the ? 写这个就像你通常会写一个insert语句一样,但是你通常会在VALUES中插入/选择数据等等,使用 placeholder for each field in the database tables you want to pass data into. 要将数据传入的数据库表中每个字段的占位符。

Now lets break down the next line: 现在让我们分解下一行:

db.transaction(function(tx) {tx.executeSql(sqlTxt,[val1,val2,val3])}, errorCB, successCB);

When you create a new database, db is the handler to the database object so db.transaction asks to execute a transaction on the database db. 创建新数据库时,db是数据库对象的处理程序,因此db.transaction要求在数据库db上执行事务。

If we write next next section like this you can see it's function that calls tx.executeSql and because it in execute inside the db.transaction method, it will be passed the db handle. 如果我们在下一节这样写下你可以看到它调用tx.executeSql的函数,并且因为它在db.transaction方法中执行,它将被传递给db句柄。

function(tx) {
    tx.executeSql(sqlTxt,[val1,val2,val3])
}

Now if we were to parse the sqlTxt it might look like this 现在,如果我们要解析sqlTxt,它可能看起来像这样

INSERT INTO demo (geo1, geo2, geo3) VALUES ('a', 'b', 'c');

and because we are passing the three variable in place of the ? 因为我们正在传递三个变量代替 holder, it looks like the line above. 持有人,它看起来像上面的线。 And finally you call error and success callback functions. 最后,您调用错误和成功回调函数。

In your case I would create a queryDB function like this: 在你的情况下,我将创建一个这样的queryDB函数:

function queryDB(id) {
    var sqlTxt = "SELECT * FROM DEMO WHERE id=?"
    db.transaction(function(tx) {tx.executeSql(sqlTxt,[id])}, errorCB, successCB);
}

In essence, the function grabs the parameter id, passes it into the query in the [id] and executes and returns error or success. 实质上,该函数获取参数id,将其传递给[id]中的查询并执行并返回错误或成功。 Obviously you can extend this to use multiple parameters or if you want to be really clever, you just create a single database transaction function and pass in the sql and the parameters to use as an object or array (Example will be on my blog this weekend) 显然你可以扩展它以使用多个参数,或者如果你想要非常聪明,你只需创建一个数据库事务函数并传入sql和参数以用作对象或数组(示例将在本周末在我的博客上)

Wrap it in a function again 再次将其包裹在一个函数中

var id = 'THEID';
db.transaction(function(){
  queryDB(id)
}, errorCB);

Note - This is assuming that you're making the API. 注意 - 这是假设您正在制作API。 Some APIs / frameworks insert the required information automatically. 某些API /框架会自动插入所需的信息。 For example 例如

//the db.transaction method
function transaction(param, callback) {
   //do code stuff
   callback(someInternalId); //callback is the function you pass as the first parameter
}

So, if you want to pass your own data in the callback, wrap it in a function. 因此,如果要在回调中传递自己的数据,请将其包装在函数中。 Otherwise, the code you are using may be doing this for you automatically. 否则,您使用的代码可能会自动为您执行此操作。

Ok first of all create a class hat will handle you're db instances (db updates etc) this class will hold a function that you will use for all you're query's 好的,首先创建一个类帽子将处理你的db实例(db更新等)这个类将保存一个函数,你将用于所有你的查询

self.db = window.openDatabase( // and so on

then the function: 那么功能:

    // execute a query and fetches the data as an array of objects
self.executeQuery = function(string, args, callback, callbackparams) {
    var self = this;
    //console.log('db execute: '+string);
    self.db.transaction(function(tx) {
        tx.executeSql(string, args, function(tx, result) {
            var retval = [];
            for (var i = 0; i < result.rows.length; ++i) {
                retval.push(result.rows.item(i));
            }
            if (callback) {
                callback(retval, result, callbackparams);
            }

        }, self.error);
    });
}

then when u have initiated you're class (i named it myDb) go apeshit! 然后,当你开始上课时(我把它命名为myDb)去吧!

myDb.executeQuery('select l.* from location l inner join item_location il on (il.location_id = l.id and il.item_id = ?)', [item.id], function(locations, res, item){
                item.locations = locations;
                myDb.executeQuery('select * from media where item_id = ?', [item.id], function(media, res, item){
                    item.media = media;
                    // create item.
                    createItem(item);                       
                }, item);
            }, item);

as you can see the executeQuery has 4 params, query, params for query, callback (with 3 params, result, status and myparam) myparam (for callback) 正如你所看到的,executeQuery有4个参数,查询,参数查询,回调(有3个参数,结果,状态和myparam)myparam(用于回调)

It took me some time to fix this, but when you've done this! 我花了一些时间来解决这个问题,但是当你这样做的时候! no more annoying db horror! 没有更烦人的数据库恐怖!

We can't send any paramenter for queryDB function like "queryDB(id)" 我们不能发送任何queryDB函数的参数,如“queryDB(id)”

I solved this issue by this way. 我通过这种方式解决了这个问题。

var contactId = 33
dbInst.transaction(function(tx){
    tx.executeSql('CREATE TABLE IF NOT EXISTS CONTACT_REFERENCE (id unique)');
    var sqlStr = 'INSERT INTO CONTACT_REFERENCE (id) VALUES (?)'
    tx.executeSql(sqlStr, [contactId]);
}, errorCB, successCB);

I think everyone comes close to answering your question. 我想每个人都接近回答你的问题。 Really you need one slight modification to JohnP's answer. 真的,你需要对JohnP的答案稍作修改。 You should pass in the SQLTransaction Object that carries the executeSQL function. 您应该传入带有executeSQL函数的SQLTransaction对象。 So to build on John's answer: 所以以John的答案为基础:

var id = 'THEID';
db.transaction(function(tx){
  queryDB(tx, id)
}, errorCB);

Then where you define the function you can grab your id param with an extra variable. 然后在定义函数的地方,您可以使用额外的变量获取id参数。

queryDB: function (tx, id) { ...your code... }

This is a worked solution: 这是一个有效的解决方案:

var sqltxt= 'INSERT INTO CONTACTS(id, data) VALUES (?, ?)';
    var db = window.openDatabase("Database", "1.0", "Demo", 200000);
    db.transaction(function(tx){tx.executeSql('DROP TABLE IF EXISTS CONTACTS');
            tx.executeSql('CREATE TABLE IF NOT EXISTS CONTACTS(name unique, password)');

            tx.executeSql(sqltxt,[name, pass]);

    }, errorCB, successCB);

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

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