ExpressJs Connecting to Databases
Syntax
const mysql = require('mysql');
const express = require('express');
const app = express();
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'password',
database : 'test'
});
connection.connect();
app.get('/', (req, res) => {
connection.query('SELECT * FROM users', (err, rows) => {
if (err) {
res.status(500).send('Something went wrong');
}
res.json(rows);
});
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
Example
In this example, we're connecting to a MySQL database and retrieving all rows from the "users" table. We're using the mysql
package to create a new connection, and then querying the database using that connection.
Explanation
In order to connect to a database in ExpressJs, we first need to create a connection object using the appropriate package for the selected database, in this case, we are using the mysql
package. Once we have the connection object, we can query the database using the query()
method.
In the example above, we're connecting to a MySQL database on localhost using the mysql
package. Once we have created the connection, we define an Express route that retrieves all rows from the "users" table. Finally, we start the Express server and listen on port 3000.
Use
Connecting to a database is a common requirement in most web applications. ExpressJs provides a convenient way to connect to, and query databases using the appropriate package for the database engine.
Important Points
- Always ensure that you have the appropriate package installed for the database engine you intend to use.
- Always check for errors when querying a database and handle them appropriately.
- Include appropriate authentication credentials, such as the username and password, when creating a connection object.
Summary
Connecting to a database is an important aspect of building web applications. In this article, we saw how to connect to a MySQL database using the mysql
package, query the database, and how to incorporate the database connection to an Express server application.