gpt4 book ai didi

javascript - 使用参数插入 SQLite 数据库

转载 作者:搜寻专家 更新时间:2023-10-30 20:36:15 25 4
gpt4 key购买 nike

我正在使用 AngularJS、Monaca 和 OnsenUI 构建跨平台应用。

我已经实现了一个 SQLite 数据库来保存数据以便能够离线工作。我的实现基于找到的答案 HERE

我有一个 View ,用户可以在其中选择任意数量的选项,然后应将这些选项值保存到 SQLite 数据库中。每个选项值都可以保存到同一个数据库表或单独的表中 - 取决于所选的选项值。

有了这个,我正在尝试重构我的插入语句以使其更高效,因为它可能会被多次调用。在我的 app.js Controller 中,我有一个函数检查在 View 中选择了哪个选项值,然后调用 goInsert() 函数将选定的选项值插入到 SQLite 数据库中。下面是我的函数示例。

$scope.selectedIDOne = ""; // Variable to hold selected options value

$scope.changedValue = function (item, identifier) // item = selected option value; identifier = identifies table name to insert into
{
switch (identifier)
{
case "Square":
$scope.selectedIDOne = item;
db.transaction(goInsert(identifier), errorCB, successCB); // Error on refactored goInsert(identifier) function trying to pass identifier
break;

default:
// TODO
}
}

然后我在 goInsert() 函数中尝试以下操作。

function goInsert(identifier) // Error here
{
switch (identifier)
{
case "Square":
db.transaction(insertSquareDB, errorCB, successCB);
break;
}
}

function insertSquareDB(tx)
{
tx.executeSql('INSERT OR IGNORE INTO tb_square (square_id) VALUES ("' + $scope.selectedIDOne + '" )');
}

当我运行代码时,我在指示的位置收到错误,但该值仍然插入到数据库中。在 goInsert(identifier) 函数调用时抛出错误。错误是:

类型错误:无法在“数据库”上执行“事务”。作为参数 1 提供的回调不是函数。

请问我该如何实现这个解决方案?或者,还有更好的方法?理想情况下,我也不想创建多个 insertSquareDB(tx) 函数,例如insertCircleDB(tx)、insertRoundDB(tx) 等。有没有一种方法可以定义 1 个动态插入值的函数,例如(假设)

function insertSquareDB(tx, tableName, columnName, optionValues) 
{
tx.executeSql('INSERT OR IGNORE INTO tableName (columnName) VALUES ("' + optionValues + '" )');
}

最佳答案

您不需要将 goInsert(identifier) 调用包装在事务中:

switch (identifier)
{
case "Square":
$scope.selectedIDOne = item;
goInsert(identifier);
...
}

如果您希望能够调用一个函数将任何形状插入数据库,最好的办法是动态生成 SQL 语句:

function insertShapeDB(shape, value) 
{
var tableName = '';
var columnName = '';
if (shape === 'Square') {
tableName = 'tb_square';
columnName = 'square_id';
}
else if (shape === 'Circle') {
tableName = 'tb_circle';
columnName = 'circle_id';
}
else if (shape === 'Round') {
tableName = 'tb_round';
columnName = 'round_id';
}
var sql = 'INSERT OR IGNORE INTO ' + tableName + ' (' + columnName + ') VALUES (?)';
db.transaction(function(tx) {
tx.executeSql(sql, [value]);
});
}

关于javascript - 使用参数插入 SQLite 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38339453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com