nodejs query database example
nodejsTo query a database from a Node.js application, you can use a library like mysql2 or pg (which is a PostgreSQL client for Node.js).
Here is an example of how you can use the mysql2 library to connect to a MySQL database, execute a query, and print the results:
const mysql = require('mysql2');
// Create the connection to the database
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'test',
password: 'password'
});
// Execute a query
connection.query(
'SELECT * FROM users WHERE name = ?',
['Alice'],
(err, results, fields) => {
console.log(results); // results contains rows returned by the query
console.log(fields); // fields contains extra meta data about results, if available
}
);
// Close the connection
connection.end();
This example queries the users table for all rows where the name column is ‘Alice’, and prints the results to the console.
You can use a similar approach to query a PostgreSQL database using the pg library.
Other Article on Tag nodejs
- - axios Request path contains unescaped characters
- - CryptoJS.HmacSHA256 Cannot read properties of undefined (reading 'sigBytes')
- - encrypt by java and decrypt by node
- - fetch function mode sors, no-cors, same-origin
- - How to set value for NODE_TLS_REJECT_UNAUTHORIZED
- - it error Request path contains unescaped characters
- - java vs nodejs
- - nodejs add redis
- - nodejs call api get request
- - nodejs connect mysql database