1

**I connected to the Postgres server using Nodejs and now I want to see all the databases under the connected server. Please help me **

Satish0302
  • 118
  • 3
  • 8
  • The question doesn't appear to include any attempt at all to solve the problem. Please edit the question to show what you've tried, and show a specific roadblock you're running into with [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). For more information, please see [How to Ask](https://stackoverflow.com/help/how-to-ask). – Andreas Jan 07 '20 at 07:15
  • Hi user8453485 Welcome to StackOverFlow. Below is the SQL to provide all the databases on the current server that you're connected to. –  Jan 07 '20 at 07:34

2 Answers2

5

Please see below for mysql database:

var mysql = require('mysql');
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});

con.connect(function(err) {
  if (err) throw err;
  con.query("show databases", function (err, result, fields) {
    if (err) throw err;
    console.log(result);
  });
});
  • This assumes you know a database during the creation of con. What if I want to dynamically determine the databases and then use one? – Aditya Mittal Jan 19 '22 at 09:58
1

SQL

SELECT datname FROM pg_database
WHERE datistemplate = false;

Example

const { Pool, Client } = require('pg')
const pool = new Pool({
user: 'dbuser',
host: 'database.server.com',
database: 'mydb',
password: 'password',
port: 5432,
})
pool.query('SELECT NOW()', (err, res) => {
console.log(err, res)
pool.end()
})
const client = new Client({
user: 'dbuser',
host: 'database.server.com',
database: 'mydb',
password: 'secretpassword',
port: 3211,
})
client.connect()
client.query('SELECT datname FROM pg_database WHERE datistemplate = false;', (err, res) => { console.log(err, res) client.end() }
)
  • Thanks, Sir, It's working. I need all the list of the database so I used this line. client.query('SELECT * FROM pg_database WHERE datistemplate = false;', (err, res) => { console.log(err, res) client.end() } ) – Satish0302 Jan 07 '20 at 10:53