使用带有数组的WebSQL的In运算符

时间:2014-09-08 19:10:45

标签: javascript web-sql

searchSQL: "SELECT * FROM FOLIO where productID IN(?)",

search: function(q, productIds) {
    var self = this;
    this.database.transaction(function(transaction) {
        transaction.executeSql(self.searchSQL, [productIds.join(", ")], function(transaction, resultSet){self.search_transactionComplete(transaction, resultSet)}, function(error){self.searchTransactionError()});
    });
},

search_transactionComplete: function(transaction, resultSet) {
    console.log(transaction, resultSet);
},

searchTransactionError: function(error) {console.log(this.constructor.NAME, this.searchSQL); console.log(error);},

任何人都可以建议我如何在WebSQL / Javascript中使用带有传递数组(productIds)的IN运算符。

1 个答案:

答案 0 :(得分:2)

我意识到这可能有点晚了,但是如果有其他人遇到这个问题,这就是我的hacky解决方法。我知道它并不理想,但据我所知,webSQL不支持数组类型参数;我的解决方案动态生成sql,并将产品数组中的每个项目作为单独的参数传递。

search: function(q, productIds) {
var self = this;

if (productIds.length == 0) {
    //no-op
} else {
    //make a copy of the productIds array
    var paramList = productIds.slice();

    //replace all values in the array with a parameter-placeholder
    for (var ii = 0; ii < paramList.length; ii++) {
        paramList[ii] = '?';
    }

    //convert the list of parameters to a comma-delimited string
    var sParamList = paramList.join();

    //we know sParamList is clean, it can only contain commas and question marks
    var hackySql = "SELECT * FROM FOLIO where productID IN(" + sParamList + ")";

    //hackySQL looks like: "SELECT * FROM FOLIO WHERE productID IN(?,?,?,?,?,?)"

    this.database.transaction(function(transaction) {
        transaction.executeSql(hackySql, productIds,   function(transaction, resultSet){self.search_transactionComplete(transaction, resultSet)}, function(error){self.searchTransactionError()});
    })
}}

希望这有助于其他人!