Using the mysql library
Node.js is able to connect to MySQL database servers, but support for this is not built in. We need to make use of a Node.js package that handles the low level details of establishing a connection and talking to the database. Additionally, such a package should enable us to issue statements to the database written in SQL.
The most widely accepted NPM package for this is simply named mysql
.
In order to use it, let's start by declaring mysql
as a dependency for our project in our package.json
file:
{ "dependencies": { "mysql": "^2.12.0" } }
As always, npm install
pulls in everything we need to start working with a MySQL database.
For what follows, I assume that you have a working MySQL database up and running on your local machine. You should be able to connect to it locally. You can verify that this is the case by running mysql -h127.0.0.1 -uroot -p
on your command line. Provide the database root password if needed – you will also need this password in your...