我正在尝试创建一个节点应用程序,该应用程序可以通过创建数据库,然后创建表和字段来在数据库端进行自我设置。以下是我用来彼此独立执行每个任务的两个函数。我可以在如何将它们结合在一起方面获得帮助吗?我应该使用pg-promise而不是pg吗?
function createDatabase(){
const pool = new pg.Pool({
user: 'postgres',
host: '127.0.0.1',
database: 'postgres',
password: 'postgres',
port: '5432'}
);
pool.query("CREATE DATABASE myApp;",
(err, res) => {
console.log(err, res);
pool.end();
});
}
function createTable(){
const pool = new pg.Pool({
user: 'postgres',
host: '127.0.0.1',
database: 'myApp',
password: 'postgres',
port: '5432'}
);
pool.query("CREATE TABLE session(sessionguid UUID NOT NULL, created
text NOT NULL, sessionlife integer NOT NULL)",
(err, res) => {
console.log(err, res);
pool.end();
});
}
答案 0 :(得分:0)
也许以下代码会为您提供帮助。现在,“ CREATE DATABASE”查询完成后,将立即在回调中创建表。
function createDatabase(){
const pool = new pg.Pool({
user: 'postgres',
host: '127.0.0.1',
database: 'postgres',
password: 'postgres',
port: '5432'}
);
pool.query("CREATE DATABASE myApp;", (err, res) => {
console.log(err, res);
pool.query("CREATE TABLE session(sessionguid UUID NOT NULL, created text NOT NULL, sessionlife integer NOT NULL)", (err, res) => {
console.log(err, res);
pool.end();
});
});
}
答案 1 :(得分:0)
为了从代码创建数据库,我使用客户端而不是池。示例如下:
const { Pool, Client } = require('pg')
const client = new Client({
user: 'postgres',
host: 'localhost',
password: 'postgres',
port: 5432
})
await client.connect()
await client.query(`DROP DATABASE IF EXISTS ${dbname};`)
await client.query(`CREATE DATABASE ${dbname};`)
await client.end()
//call the pool you just created after the database has been created.