This article describes how to connect to a PostgreSQL database using Node.js.
The node-postgres package includes all of the functionality you need to access and work with PostgreSQL databases in Node.js. Before you can do this, however, you must install the node-postgres package on your account. To do this, follow these steps:
cd ~ npm install pg
After you install the node-postgres package, you are ready to work with PostgreSQL databases and manipulate data in them. The following sample Node.js code demonstrates how to do this.
In your own code, replace dbname with the database name, username with the PostgreSQL database username, and password with the database user's password. Additionally, you should modify the SELECT query to match a table in your own database:
import pg from 'pg'; const { Client } = pg; const client = new Client({ host: 'localhost', database: 'dbname', user: 'username', password: 'password', }); await client.connect(); const res = await client.query('SELECT fname, lname FROM employee'); console.log(res.rows[0]); await client.end();
In this example, we first instantiate a Client object that specifies a connection to a PostgreSQL database.
After we call the connect() method on the client object, we can run raw SQL statements such as SELECT.
Finally, we call the end() method to close the client's connection to the database.
You may receive the following error message when you try to run this code:
SyntaxError: Cannot use import statement outside a module
If you receive this error message, create a package.json file in the same directory as the code file. Copy the following text and then paste it into the package.json file:
{ "type": "module" }
The code should now run.
For more information about the node-postgres package, please visit https://node-postgres.com/.
Subscribe to receive weekly cutting edge tips, strategies, and news you need to grow your web business.
No charge. Unsubscribe anytime.
Did you find this article helpful? Then you'll love our support. Experience the A2 Hosting difference today and get a pre-secured, pre-optimized website. Check out our web hosting plans today.
We use cookies to personalize the website for you and to analyze the use of our website. You consent to this by clicking on "I consent" or by continuing your use of this website. Further information about cookies can be found in our Privacy Policy.