如何通过 Node.js 连接到 SQLite3 [英] How to make connection to SQLite3 via Node.js

查看:30
本文介绍了如何通过 Node.js 连接到 SQLite3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注 The Node Craftsman Book 并发现自己一直无法连接到 SQLite3 数据库.

I am following The Node Craftsman Book and have found myself stuck on connecting to the SQLite3 database.

根据这本书,我应该能够使用 DBWrapper 并包含一个路径,如下面 dbSessions.js 的屏幕截图所示:

According to the book, I should be able to use DBWrapper and include a path as shown in the screencap of dbSessions.js below:

我知道数据库存在,因为我可以使用 DB Browser for SQLite 打开它.

I know the database exists, because I'm able to open it using DB Browser for SQLite.

我知道服务器正在运行:

I know the server is running:

Server started and listening on port 8080

但是当我运行测试时,它超时了.我怎么知道我是否正在连接?即使我不相信我在连接.

But when I run my test, it times out. How can I even tell if I am connecting? Even though I don't believe I am connecting.

我能找到的最接近的信息是 mlccetti 在这里的回答.也许书中的说明不正确?或者我错过了什么?

The closest information I could fine is in mlaccetti's answer here. Perhaps the instructions in the book are incorrect? Or what am I missing?

这是我的代码:

index.js

'use strict';

var percolator = require('percolator').Percolator;
var dbSession = require('./dbSessions.js');

var port = 8080;
var server = percolator({'port': port, 'autoLink': false});

server.route('/api/keywords',
    {
        GET: function(req, res) {
            dbSession.fetchAll('SELECT id, value, categoryID FROM keyword ORDER BY id',
            function(err, rows) {
                if(err) {
                    console.log(err);
                    res.status.internalServerError(err);
                } else {
                    res.collection(rows).send();
                }

            });
        }
    }
);

server.listen(function(req, res) {
    console.log('Server started and listening on port', port);
});

dbSessions.js

'use strict';

var DBWrapper = require('node-dbi').DBWrapper;
var dbWrapper = new DBWrapper('sqlite3', {'path': '../../data/keyword-wrangler2.test.sqlite'});

dbWrapper.connect();

module.exports = dbWrapper;

apiSpec.js

'use strict';

var request = require('request');
var dbSession = require('../../src/backend/dbSessions.js');
var resetDatabase = require('../resetDatabase.js');
var async = require('async');

describe('The API', function() {
    it('should respond to a GET request at/api/keywords', function(done) {
        var expected = {
            "_items": [
                {'id': 1, 'value': 'Aubergine', 'categoryID': 1},
                {'id': 2, 'value': 'Onion', 'categoryID': 1},
                {'id': 3, 'value': 'Knife', 'categoryID': 2}
            ]
        };

        async.series(
                [

                    function(callback) {
                        resetDatabase(dbSession, callback);
                    },

                    function(callback) {
                        dbSession.insert(
                                'keyword',
                                {'value': 'Aubergine', 'categoryID': 1},

                        function(err) { callback(err); });
                    },

                    function(callback) {
                        dbSession.insert(
                                'keyword',
                                {'value': 'Onion', 'categoryID': 1},

                        function(err) { callback(err); });
                    },

                    function(callback) {
                        dbSession.insert(
                                'keyword',
                                {'value': 'Knife', 'categoryID': 2},

                        function(err) { callback(err); });
                    }

                ],

                function(err, results) {
                    request.get(
                            {
                                'url': 'http://localhost:8080/api/keywords/',
                                'json': true
                            },
                            function(err, res, body) {
                                expect(res.statusCode).toBe(200);
                                expect(body).toEqual(expected);
                                done();
                            }
                        );
                }
            );

    });
});

推荐答案

在我开始尝试提供帮助之前,您最好在某处放置一个包含代码的 git repo;尝试从几个文件(即 package.json、test 等)重新创建您的项目非常耗时,而且我不太可能再次这样做.

Before I get to trying to help, it might be better for you to put up a git repo somewhere with the code; trying to re-create your project from a few files (i.e. the package.json, test, etc.) was time consuming and not something I'm likely to do again.

话虽如此,我确实试了一下,认为最可能的情况是打开数据库文件时出现问题.dbWrapper.connect() 实际上不是同步的,所以在建立连接时使用回调来确保事情实际上是有效的可能是有意义的.仅出于测试目的,我执行了以下操作:

That said, I did take it for a spin, and think that the most likely scenario is that there is a problem opening the database file. The dbWrapper.connect() is not actually synchronous, so it might make sense to use a callback when establishing the connection to ensure that things are actually alive. Just for testing purposes, I did the following:

dbWrapper.connect(function(err) {console.log('连接到数据库:', err);});

虽然我创建了 sqlite DB 文件,但根据我运行应用程序的方式,路径引用是错误的(即 node src/index.js 使 ../data 我使用的路径不正确,报告了以下错误:Connected to DB: { [Error: SQLITE_CANTOPEN: cannot open database file] errno: 14, code: 'SQLITE_CANTOPEN' }

While I had created the sqlite DB file, the path reference was wrong based on how I was running the application (i.e. node src/index.js made the ../data path that I was using incorrect, and the following error was reported: Connected to DB: { [Error: SQLITE_CANTOPEN: unable to open database file] errno: 14, code: 'SQLITE_CANTOPEN' }

一旦我修改了路径,它就可以找到该文件,而且这似乎奏效了.

Once I modified the path, it could find the file, and that seems to have worked.

PS - node-dbi 已经两年没动过了,所以可能不是最好的选择.

PS - node-dbi hasn't been touched in two years, so might not be the best choice.

这篇关于如何通过 Node.js 连接到 SQLite3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆