是否可以使用pg-promise和PostgreSQL(9.5)“创建数据库…”?

时间:2021-10-11 15:37:04

Question is:

问题是:

1) Can pg-promise be used to create a new database (schemas, et. al.)?

Using node package 'pg-promise' I can't seem to figure out if it's possible to create a new database. I can connect to an existing database and have no issue there. However, when I run without a database name I get an error:

使用节点包“pg-promise”,我似乎不知道是否有可能创建一个新的数据库。我可以连接到现有的数据库,在那里没有问题。但是,当我在没有数据库名的情况下运行时,会出现一个错误:

This is what I am trying:

这就是我正在尝试的:

host = host || '127.0.0.1'
port = port || '5432'

const pgp = require('pg-promise')(pgpInitOptions)

// database connection details
const pgConnectionOptions = {
  host: host,
  port: port,
  user: user,
  password: pass
}

// database instance
const localDB = pgp(pgConnectionOptions)

let escapedDbName = dbName.replace(/\"/g, '""');
let sql = 'CREATE DATABASE "' + escapedDbName + '"';

localDB
.any(sql)
.then((results) => {
  console.log('creation of database successful', results)
})
.catch((error) => {
  console.error('creation of database failed', error)
})

Then, I get this error:

然后,我得到这个错误:

creation of database failed
Error: database "jeff" does not exist

"jeff" is my ubuntu login name.

“jeff”是我的ubuntu登录名。

1 个解决方案

#1


3  

First, you need to connect to an existing database, using an admin account which has the right to create new databases.

首先,您需要连接到一个现有的数据库,使用一个有权创建新数据库的管理帐户。

Then you can create new databases via a regular query...

然后,您可以通过一个常规查询创建新的数据库。

const pgp = require('pg-promise')(/* initialization options */);

const db = pgp({
    database: 'any-existing-db',
    port: 5432,
    user: 'postgres', // any admin user
    password: 'admin-password'
});

db.none('CREATE DATABASE $1:name', 'my_database')
    .then(data => {
        console.log('successfully created');
    })
    .catch(error => {
        console.log(error);
    });

I am running such code locally, and it works fine.

我正在本地运行这样的代码,它工作得很好。

#1


3  

First, you need to connect to an existing database, using an admin account which has the right to create new databases.

首先,您需要连接到一个现有的数据库,使用一个有权创建新数据库的管理帐户。

Then you can create new databases via a regular query...

然后,您可以通过一个常规查询创建新的数据库。

const pgp = require('pg-promise')(/* initialization options */);

const db = pgp({
    database: 'any-existing-db',
    port: 5432,
    user: 'postgres', // any admin user
    password: 'admin-password'
});

db.none('CREATE DATABASE $1:name', 'my_database')
    .then(data => {
        console.log('successfully created');
    })
    .catch(error => {
        console.log(error);
    });

I am running such code locally, and it works fine.

我正在本地运行这样的代码,它工作得很好。