【问题标题】:How to create table after first creating a database with Node and pg首次使用 Node 和 pg 创建数据库后如何创建表
【发布时间】:2019-02-05 20:37:36
【问题描述】:

我正在尝试创建一个节点应用程序,该应用程序可以通过创建数据库然后创建表和字段来在数据库端设置自己。下面是我用来独立完成每项任务的两个函数。我可以就如何将这些组合在一起获得一些帮助吗?我应该使用 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();
});

}

【问题讨论】:

标签: node.js postgresql pg


【解决方案1】:

也许下面的代码会对你有所帮助。现在将在“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();
    });
});
}

【讨论】:

  • 几乎,但这让我面临下一个挑战,以及为什么我没有尝试您的解决方案。连接中的数据库是 postgres,所以当创建表被触发时,它是在 postgres 数据库中创建的,而不是在它之前的行中创建的新表。
【解决方案2】:

为了从代码创建数据库,我使用客户端而不是池。示例如下:

        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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-25
    • 2021-08-11
    • 2012-03-02
    • 2015-09-15
    • 1970-01-01
    • 2014-01-15
    • 2012-02-21
    • 2017-09-13
    相关资源
    最近更新 更多