gpt4 book ai didi

javascript - 使用node.js从数据库获取数据

转载 作者:行者123 更新时间:2023-12-02 16:03:26 24 4
gpt4 key购买 nike

我使用简单的 Node 示例启动node.js。

我的简单项目提供从数据库获取数据(从 bla bla bla 选择*),但我有一个问题如下:

Error: No such database: hakan_billur
at Connection.parseE (C:\Users\hakan_billur\workspace\postgre-bilgi2\node_modules\pg\lib\connection.js:539:11)
at Connection.parseMessage (C:\Users\hakan_billur\workspace\postgre-bilgi2\node_modules\pg\lib\connection.js:366:17)
at Socket.<anonymous> (C:\Users\hakan_billur\workspace\postgre-bilgi2\node_modules\pg\lib\connection.js:105:22)
at Socket.emit (events.js:107:17)
at readableAddChunk (_stream_readable.js:163:16)
at Socket.Readable.push (_stream_readable.js:126:10)
at TCP.onread (net.js:538:20)
Program node ./bin/www exited with code 1

database.js如下:

var pg = require('pg');
var path = require('path');
var connectionString = require(path.join(__dirname, '../', '../', 'config'));

config.js如下:

var connectionString = process.env.DATABASE_URL || 'postgres://portal:por**tal@10.10.22.105:6432';

module.exports = connectionString;

index.js如下:

var express = require('express');

var router = express.Router();

var path = require('path');
var pg = require('pg');

var connectionString = require(path.join(__dirname, '../', '../', 'config'));

router.get('/', function(req, res, next) {
var results = [];

var client = new pg.Client(connectionString);
client.connect();

// Get a Postgres client from the connection pool
pg.connect(connectionString, function(err, client, done) {

// SQL Query > Insert Data
var query = client.query("SELECT * FROM poll where is_active=true");

query.on('row', function(row) {
results.push(row);
});

console.log(results);

// After all data is returned, close connection and return results
query.on('end', function() {
client.end();
console.log(results);
return res.json(results);
});

// Handle Errors
if(err) {
console.log(err);
}
});

res.sendFile(res.render(path.join(__dirname, '../', '../', './client', 'views', 'index')));

});

最终文件层次结构如下:

enter image description here

谁可以帮助我。预先感谢您的帮助。

最佳答案

您的连接字符串中缺少数据库名称。

字符串语法如下:

var cn = "postgres://username:password@host:port/database";

或者,您可以使用对象:

var cn = {
host: 'localhost', // server name or IP address;
port: 5432,
database: 'my_db_name',
user: 'user_name',
password: 'user_password'
};

pg模块可以自动识别正在使用的是哪一个。

附注要顺利开始使用 PosgreSQL 和 Node JS,请查看 pg-promise ;)

关于javascript - 使用node.js从数据库获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30979473/

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