在 HTML5 页面中使用 JavaScript 连接到 SQLite 数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8338116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:06:17  来源:igfitidea点击:

Using JavaScript in a HTML5 page to connect to a SQLite database

javascriptsqlitehtml

提问by jester113

I'm trying to make a simple word game that has a database of words (which is preloaded or can be loaded by the user) that can be updated through website. I found thisexample and I got it to work. However, it wont work if I have an existing database. I'm new to this type of programming, so i've been doing research for 2 days now.

我正在尝试制作一个简单的文字游戏,它有一个可以通过网站更新的单词数据库(预加载或可由用户加载)。我找到了这个例子,我让它工作了。但是,如果我有一个现有的数据库,它就行不通。我是这种编程的新手,所以我已经研究了 2 天。

var db = openDatabase('db.sqlite', '1.0', 'Test DB', 2 * 1024 * 1024);
var msg;
/*
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS vocabList(id unique, word, definition, weekNO)');
msg = '<p>Log message created and row inserted.</p>';
document.querySelector('#status').innerHTML =  msg;
});
*/ 

I commented this out to prevent creating the database (should i have not done that?)

我将其注释掉以防止创建数据库(我不应该这样做吗?)

db.transaction(function(tx) {
    tx.executeSql('SELECT * FROM vocabList WHERE weekNO = 1', [], function(tx, results) {
        var len = results.rows.length,
            i;
        msg = "<p>Found rows: " + len + "</p>";
        document.querySelector('#status').innerHTML += msg;
        for (i = 0; i < len; i++) {
            msg = "<p><b>" + results.rows.item(i).word + "</b></p>";
            document.querySelector('#status').innerHTML += msg;
        }
    }, null);
});

If there is another more efficient way to do this, please point me in the right direction.

如果有另一种更有效的方法来做到这一点,请指出正确的方向。

回答by Vigrond

I'm not exactly sure what you're having problems with. But in your code, you commented out the part where it checks whether or not a table has been created. From that commented out code, there are no rows being inserted either, so it is a blank database.

我不太确定你有什么问题。但是在您的代码中,您注释掉了检查是否已创建表的部分。从注释掉的代码中,也没有插入任何行,因此它是一个空白数据库。

I modified your code here: http://jsfiddle.net/Ae8m2/

我在这里修改了你的代码:http: //jsfiddle.net/Ae8m2/

I uncommented out your creation part, and added a couple rows.

我取消了您的创作部分的注释,并添加了几行。

回答by Nathan

The database you are creating/connecting to is a client-sidedatabase. If you want to connect to a back-enddatabase, you should use a server language, such as php.

您正在创建/连接的数据库是客户端数据库。如果要连接到后端数据库,则应使用服务器语言,例如php.

You may want to use ajax with this, to connect to your database and execute your requests.

您可能希望使用 ajax 来连接到您的数据库并执行您的请求。