MySQL是世界上最流行的关系型数据库之一。了解如何让它与Node.js一起工作
MySQL是世界上最流行的关系型数据库之一。
当然,Node生态系统有几个不同的包,允许你与MySQL对接,存储数据,检索数据,等等。
我们将使用 mysqljs/mysql,这个包在GitHub上有超过12,000颗星,已经存在了很多年。
安装Node的mysql包
你用以下方式安装它
初始化与数据库的连接
你首先包括该包。
const mysql = require('mysql')
并且你创建一个连接。
const options = {
user: 'the_mysql_user_name',
password: 'the_mysql_user_password',
database: 'the_mysql_database_name'
}
const connection = mysql.createConnection(options)
你通过调用启动一个新的连接。
connection.connect(err => {
if (err) {
console.error('An error occurred while connecting to the DB')
throw err
}
})
连接选项
在上面的例子中,options 对象包含3个选项。
const options = {
user: 'the_mysql_user_name',
password: 'the_mysql_user_password',
database: 'the_mysql_database_name'
}
你可以使用更多的选项,包括。
host,数据库主机名,默认为localhostport,MySQL服务器端口号,默认为3306socketPath, 用于指定一个unix套接字,而不是主机和端口debug, 默认为禁用,可用于调试trace, 默认为启用,当发生错误时打印堆栈痕迹ssl浏览器,用于设置与服务器的SSL连接(不在本教程范围内)。
执行一个SELECT查询
现在你已经准备好在数据库上执行一个SQL查询。查询一旦执行,将调用一个回调函数,其中包含一个最终的错误、结果和字段。
connection.query('SELECT * FROM todos', (error, todos, fields) => {
if (error) {
console.error('An error occurred while executing the query')
throw error
}
console.log(todos)
})
你可以传入值,这些值将被自动转义。
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)
})
要传递多个值,只需在你作为第二个参数传递的数组中放入更多元素。
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)
})
执行一个INSERT查询
你可以传递一个对象
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
}
})
如果表有一个带有auto_increment 的主键,其值将在results.insertId 值中返回。
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)
)
关闭连接
当你需要终止与数据库的连接时,你可以调用end() 方法。
这可以确保任何悬而未决的查询被发送,并且连接被优雅地终止。