使用JQuery读取文本文件并存储到数据库中

4

我有一个包含内容的文件

1 : "Benz"
2 : "Bmw"
3 : "Porche"
4 : "Ferrari"

我想使用Jquery读取文件,并将它们存储在OpenDataBase中的Local Database中。其中,1是步骤的编号,Benz是数据库中的另一个字段。

我的代码用于读取文件:

jQuery.get('file/words.txt', function(data) {
    alert(data)
});

我的代码用于创建数据库

var db = openDatabase( ’mydb’, ’1.0’,
                   ’database for test’,
                   2 * 1024 * 1024
                 );
db.transaction(function (tx) {
tx.executeSql(’CREATE TABLE IF NOT EXISTS Car
                (number INT, name VARCHAR(100))’);

});

我不知道如何使用JavaScript将数据分离并存入数据库。

谢谢。


这个方法可能有些奇怪,但你可以尝试接收文件并使用JavaScript的.split()将其转换为数组。 - Stardust
我认为应该使用match,但我不知道如何使用。 - joseva
2个回答

1
如果可能的话,请删除您的文本文件中的数字和引号,它们不应该被使用(计数器会为您完成这项工作)。
将读取文本文件的代码更改为以下内容:
    var file = "file/words.txt";
    function getFile(){
       $.get(file, function(txt){
           var lines = txt.responseText.split("\n");
           for (var i = 0, len = lines.length; i < len; i++) {
               save(lines[i]);
           }
       }); 
    }

现在你有一个包含文件每一行的数组;如果去掉数字和引号,它应该只是汽车名称。
for (var i = 0; i < lines.length; i++) {
   tx.executeSql('INSERT INTO Car (id, name) VALUES (i, lines[i]);
}

如果您想保留文件原样,按下面所示更改以下行:
 var lines = txt.responseText.split(":");

现在数组中包含数字和汽车名称(奇数为数字,偶数为汽车名称)。 我们可能希望摆脱双引号(SQL 可能会在这些上面出错):
lines.replace(/"/g, '').trim();

 for (var i = 0; i < lines.length; i++) {
       tx.executeSql('INSERT INTO Car (id, name) VALUES (i, lines[i+1])');
       i++; // we iterate again because we want an odd number 
            // (we skip over one iteration as that'd be the car, and we want the next # instead). 
    }

不幸的是,我需要数字和引号。实际上文件已经存在,我应该使用它。数字意味着步骤1的结果将是奔驰,步骤2的结果将是宝马。 - joseva
@joseva 这很好,修改代码相对简单。只需将".split("\n")"更改为".split(":")",因为这是 # 和汽车名称之间的分隔符。我会在我的答案中更新更多细节。 - Boris

1
这是代码,你想要什么就做什么:
// assume this is your data (I've added the newline as well)
var textData = '1 : "Benz" \n2 : "Bmw" \n3 : "Porche"\n4 : "Ferrari" ';

// turn data into array
var ary = textData.split('\n').map(function(v) {
    return v.split(':').map(function(v2) {
        // make sure we remove the quotes and spaces
        return v2.replace(/"/g, '').trim();
    });
})

// function to escape double quotes to prevent sql injection
function escapeSql(str) {
    return (typeof str === 'number' ? str : str.replace(/"/g, '"'));
}

// open database
var db = openDatabase('mydb', '1.0', 'database for test', 2 * 1024 * 1024);

// create table
db.transaction(function(tx) {
    tx.executeSql('create table if not exists Car(step, make)');
});

// insert data
db.transaction(function(tx) {
    // loop through each item and insert the data, notice how we call escapeSql to prevent sql injection
    ary.forEach(function(item) {
        var sql = 'insert into Car(step, make) values(' + escapeSql(item[0]) + ', "' + escapeSql(item[1]) + '")';
        tx.executeSql(sql);
    });
});

var sql,
    cars = [];

// read data from table
db.transaction(function(tx) {
    tx.executeSql('select * from Car', [], function(tx, results) {
        var len = results.rows.length;
        for (var i = 0; i < len; i++) {
            cars.push({
                step: results.rows.item(i).step,
                make: results.rows.item(i).make
            });
        }

        console.log(cars);
    }, null);
});

输出:

enter image description here


感谢你的代码,特别是注释。它有效果。 - joseva

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接