Exercise 13: Connecting to the Database

Now that we have created out database, in this exercise we are going to connect our application to our database using the necessary npm packages, that is, knex and mysql:

  1. On the Terminal, change directory to the root of our project, and run the following command:
npm install mysql knex --save
  1. Let's create a file db.js and add the following code to it, replacing the user and password appropriately if need be:
const env = process.env.NODE_ENV || 'development';
const configs =
{
development:
{
client: 'mysql',
...
const Knex = require('knex')(configs[env]);
module.exports = Knex;

You can find the complete code from the db.js file at Code/Lesson-3/exercise-a.
  1. Let's test that we have our configurations right. We will create a test-db.js file:
const Knex = require('./db');
Knex.raw('select 1+1 as sum')
.catch((err) => console.log(err.message))
.then(([res]) => console.log('connected: ', res[0].sum));
  1. Now, let's go to the Terminal and run the test file:
node test-db.js

You should get the following printed:

connected: 2
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset