2016-08-06 92 views
0

我想從node.js postgres sql中刪除一個名爲test的數據庫,但它不起作用。如何使用node.js在postgres sql中刪除數據庫?

var express = require('express'); 
var app = express(); 
var pg = require('pg'); 
var pgp = require('pg-promise')(); 

// Connect to PostgreSQL database 
var connectionString = process.env.DATABASE_URL || 'postgres://postgres:[email protected]:5432/test'; 
var db = pgp(connectionString); 
db.connect(); 


    db.query("DROP DATABASE test").then(function() 
    { 
    //createDatabases(db); 
    }).catch(function(err) 
    { 
    console.log(err); 
    }); 

但我得到一個錯誤

{ [error: cannot drop the currently open database] 
    name: 'error', 
    length: 87, 
    severity: 'ERROR', 
    code: '55006', 
    detail: undefined, 
    hint: undefined, 
    position: undefined, 
    internalPosition: undefined, 
    internalQuery: undefined, 
    where: undefined, 
    schema: undefined, 
    table: undefined, 
    column: undefined, 
    dataType: undefined, 
    constraint: undefined, 
    file: 'dbcommands.c', 
    line: '834', 
    routine: 'dropdb' } 

有誰知道如何解決它?

謝謝

+0

你不應該叫'db.connect();'那裏。你不應該在那裏包含'pg'。 –

回答

1

由於錯誤說,你不能連接到有問題的數據庫刪除它。您可以連接到不同的數據庫中爲了做到這一點,或使用工具,如pgtools

var pgtools = require('pgtools'); 

// This can also be a connection string 
// (in which case the database part is ignored and replaced with postgres) 

const config = { 
    user: 'postgres', 
    password: 'some pass', 
    port: 5432, 
    host: 'localhost' 
} 


pgtools.dropdb(config, 'test-db', function (err, res) { 
    if (err) { 
    console.error(err); 
    process.exit(-1); 
    } 
    console.log(res); 
}); 
+1

感謝張貼這個,剛剛證實這工作得很好,從win10 git bash運行! – vapurrmaid