DEV Community

Discussion on: Connect NodeJS App With MySQL Database Hosted on a Digital Ocean Droplet (Server)

Collapse
 
ileriayo profile image
Ileriayo Adebiyi

Hi @jupjup !
Thanks for stopping by.

It follows the same idea for connecting to a PostgreSQL database on DO.
Here's the difference:

  • You'll need to install a driver for PostgreSQL rather than for MySQL. "pg" is a good choice. npm install --save pg

Afterwards, you'll create a connection object and and execute queries.
So it will look like this:

const { Client } = require('pg')

const client = new Client({
  user: 'yourdbpassword',
  host: yourhostname.com',
  database: 'yourdbname',
  password: 'yoursupersecretpassword',
  port: 3211,
})

client.connect()

client.query('SELECT NOW()', (err, res) => {
  console.log(err, res)
  client.end()
})
Enter fullscreen mode Exit fullscreen mode

Note: You may want to use a connection pool if your application makes frequent calls. Thus, rather than using Client, you will want to use Pool. Please refer to the node-postgres docs for more information.