MySQL is one of the most popular relational databases in the world. Learn how to make it work with Node.js
MySQL is one of the most popular relational databases in the world.
Of course, the Node ecosystem has several different software packages that allow you to interact with MySQL, store data, retrieve data, etc.
We will usemysqljs/mysql
, The package has more than 1.2000 GitHub stars and has been around for many years.
Install Node mysql package
You install using
npm install mysql
Initialize the connection to the database
You first include the package:
const mysql = require('mysql')
Then create a connection:
const options = {
user: 'the_mysql_user_name',
password: 'the_mysql_user_password',
database: 'the_mysql_database_name'
}
const connection = mysql.createConnection(options)
You can start a new connection by calling the following command:
connection.connect(err => {
if (err) {
console.error('An error occurred while connecting to the DB')
throw err
}
})
Connection options
In the example above,options
The object contains 3 options:
const options = {
user: 'the_mysql_user_name',
password: 'the_mysql_user_password',
database: 'the_mysql_database_name'
}
You can use more features, including:
host
Database host name, the default islocalhost
port
, the MySQL server port number, defaults to 3306socketPath
, Used to specify the unix socket instead of the host and portdebug
, Which is disabled by default and can be used for debuggingtrace
, Enabled by default, print stack trace when an error occursssl
, Used to establish an SSL connection with the server (outside the scope of this tutorial)
Execute SELECT query
Now you can execute SQL queries on the database. Once the query is executed, a callback function will be called, which contains the final error, result and fields.
connection.query('SELECT * FROM todos', (error, todos, fields) => {
if (error) {
console.error('An error occurred while executing the query')
throw error
}
console.log(todos)
})
You can pass in values that will be automatically escaped:
const id = 223
connection.query('SELECT * FROM todos WHERE id = ?', [id], (error, todos, fields) => {
if (error) {
console.error('An error occurred while executing the query')
throw error
}
console.log(todos)
})
To pass multiple values, just put more elements in the passed array as the second parameter:
const id = 223
const author = 'Flavio'
connection.query('SELECT * FROM todos WHERE id = ? AND author = ?', [id, author], (error, todos, fields) => {
if (error) {
console.error('An error occurred while executing the query')
throw error
}
console.log(todos)
})
Execute INSERT query
You can pass an object
const todo = {
thing: 'Buy the milk'
author: 'Flavio'
}
connection.query('INSERT INTO todos SET ?', todo, (error, results, fields) => {
if (error) {
console.error('An error occurred while executing the query')
throw error
}
})
If the table has a primary key, withauto_increment
, The value will be returned inresults.insertId
value:
const todo = {
thing: 'Buy the milk'
author: 'Flavio'
}
connection.query('INSERT INTO todos SET ?', todo, (error, results, fields) => {
if (error) {
console.error('An error occurred while executing the query')
throw error
}}
const id = results.resultId
console.log(id)
)
Close the connection
When you need to terminate the connection with the database, you can callend()
method:
connection.end()
This ensures that any pending queries are sent and the connection can be terminated normally.
Download mine for freeNode.js manual
More node tutorials:
- Introduction to npm package manager
- Introduction to Node.js
- HTTP request using Axios
- Where to host Node.js applications
- Use Node.js to interact with Google Analytics API
- npx node package runner
- package.json guide
- Where does npm install packages?
- How to update Node.js
- How to use or execute packages installed with npm
- package-lock.json file
- Semantic version control using npm
- Should you submit the node_modules folder to Git?
- Update all Node dependencies to the latest version
- Use Node.js to parse JSON
- Find the installed version of the npm package
- Node.js flow
- Install an older version of the npm package
- Get the current folder in Node
- How to record objects in Node
- Use export to expose functions from Node files
- Difference between node and browser
- Use Node to make HTTP POST requests
- Use Node to get HTTP request body data
- Node buffer
- A brief history of Node.js
- How to install Node.js
- How much JavaScript do you need to know to use Node?
- How to use Node.js REPL
- Node, accepts parameters from the command line
- Use Node to output to the command line
- Accept input from the command line in Node
- Use `npm uninstall` to uninstall the npm package.
- npm global or local package
- npm dependencies and devDependencies
- Node.js event loop
- Understanding process.nextTick()
- Understanding setImmediate()
- Node event emitter
- Set up an HTTP server
- Use Node to make HTTP requests
- Node fs module
- HTTP request in Node using Axios
- Use Node to read files
- Node file path
- Write file with Node
- Node file statistics
- Use file descriptors in Node
- Use folders in Node
- Node path module
- Node http module
- Combine WebSockets with Node.js
- Basic knowledge of using MySQL and Node
- Error handling in Node.js
- Pug Guide
- How to read environment variables from Node.js
- How to exit from Node.js program
- Node os module
- Node event module
- Node, the difference between development and production
- How to check if a file exists in Node.js
- How to create an empty file in Node.js
- How to delete files using Node.js
- How to get the last update date of a file using Node.js
- How to determine whether the date is today in JavaScript
- How to write a JSON object to a file in Node.js
- Why use Node.js in the next project?
- Run web server from any folder
- How to use MongoDB with Node.js
- Use Chrome DevTools to debug Node.js applications
- What is pnpm?
- Node.js runtime v8 options list
- How to solve the "missing write access permission" error when using npm
- How to enable ES modules in Node.js
- How to use Node.js to generate child processes
- How to get the parsed body and the original body at the same time in Express
- How to handle file upload in Node.js
- What is the peer dependency in the node module?
- How to write a CSV file using Node.js
- How to use Node.js to read CSV files
- Node core module
- Use Node.js to increase the number of multiple folders at once
- How to print canvas to data URL
- How to create and save images using Node.js and Canvas
- How to download images using Node.js
- How to batch rename files in Node.js
- How to get the names of all files in a folder in Node
- How to use promise and wait function based on Node.js callback
- How to test NPM packages locally
- How to check the current Node.js version at runtime
- How to use Sequelize to interact with PostgreSQL
- Use Node.js to serve HTML pages
- How to solve the error that util.pump in Node.js is not a function