0
Ionic v1を使用していて、Android KitkatのSQLiteデータベースにいくつかのJSONレコードを挿入しようとしています。私は静的変数を使用している場合、それは動作しますが、唯一の配列内の最初の項目を挿入しますが、私は動的な変数名を作成しようとする場合、私はエラーを取得する:Sqliteが動的JSONデータを挿入しない
Cannot read property 'mac_id' of undefined
私は2つの次のコードセグメントを試してみましたが、最初の作品が、唯一の第二作動しない、JSON配列内の最初の項目を挿入:
ワークス:
しかし、唯一の最初の項目(複数回)
for (var i = 0; i < data.length; i++)
{
var mac_id = data[i].mac_id;
var device_type = data[i].device_type;
var machine_id = data[i].machine_id;
var machine_name = data[i].machine_name;
var date_created = data[i].date_created;
db.transaction(function (tx) {
var query = "INSERT INTO devices (mac_id, device_type,machine_id,machine_name,date_created) VALUES (?,?,?,?,?)";
tx.executeSql(query, [mac_id , device_type , machine_id , machine_name , date_created ], function(tx, res) {
},
function(tx, error) {
console.log(' device INSERT error: ' + error.message);
});
}, function(error) {
console.log(' device transaction error: ' + error.message);
}, function() {
console.log('device INSERT ok');
});
}
を挿入0
は、あなたがトランザクション内でのループのために使うべき
for (var i = 0; i < data.length; i++)
{
db.transaction(function (tx) {
var query = "INSERT INTO devices (mac_id, device_type,machine_id,machine_name,date_created) VALUES (?,?,?,?,?)";
tx.executeSql(query, [data[i].mac_id, data[i].device_type, data[i].machine_id, data[i].machine_name, data[i].date_created ], function(tx, res) {
},
function(tx, error) {
console.log(' device INSERT error: ' + error.message);
});
}, function(error) {
console.log(' device transaction error: ' + error.message);
}, function() {
console.log('device INSERT ok');
});
}
JSON配列
[
{
"id": "3",
"mac_id": "fsdf324324",
"device_type": "redvfsdfds",
"machine_id": "3",
"machine_name": "sdfsdfsdf",
"date_created": "3322342"
},
{
"id": "2",
"mac_id": "243434",
"device_type": "fredssd",
"machine_id": "2",
"machine_name": "fdsfsdf",
"date_created": "43434"
},
{
"id": "1",
"mac_id": "1324324234",
"device_type": "bweight",
"machine_id": "1",
"machine_name": "dffdgf",
"date_created": "4324234"
}
]