Node.js教程-mysql模块

概述

Node.js中,mysql模块是实现MySQL协议的JavaScript客户端工具。Node.js程序通过与MySQL建立链接,然后可对数据进行等操作。

安装

由于mysql模块不是Node.js内置模块,需手动安装

npm i mysql

注意:若MySQL服务的版本高于8.0.4时,请安装mysql2模块,否则连接时会出现身份验证错误。

使用

连接数据库

mysql.createConnection(options) // 返回 Connection 对象

参数说明:

  • options 配置参数
    • host 主机地址。默认为localhost
    • user 用户名
    • password 密码
    • port 端口号。默认为3306
    • database 数据库名
    • charset 字符集。默认为UTF8_GENERAL_CI
    • localAddress 此IP用于TCP连接
    • socketPath 连接到 unix 域路径,有值会忽略 hostport
    • timezone 时区。默认为local
    • connectTimeout 连接超时时长,单位 毫秒。默认为不限制
    • stringifyObject 是否序列化对象
    • dateStrings 强制将timestampdatetimedate类型以字符串型返回。默认为false
    • multipleStatements 是否允许一个 query 中有多个 mysql 语句。默认为false

Connection 方法

方法 说明
connect() 建立连接
query(sql[, values][, callback]) 对数据库进行等操作
end() 在确保当前正在处理的 SQL 语句正常完成后断开连接
destroy() 立即断开连接,不管当前是否正在执行任务

Connection 属性

属性 说明
threadId 当前连接线程 ID
// 引入 mysql 模块
const mysql = require('mysql')

// 创建连接对象
const conn = mysql.createConnection({
	host: '127.0.0.1',
	port: '3306',
	database: 'node_db',
	user: 'root',
	passord: '123456'
})

// 建立连接
conn.connect()

操作数据库

查询数据
const mysql = require('mysql2')

// 创建 Connnection 实例
const conn = mysql.createConnection({
  host: '127.0.0.1',
  port: 3306,
  database: 'db',
  user: 'root',
  password: '123456'
})

// 建立连接
conn.connect()

// 无查询条件
const sql1 = "select * from talbe_name"
conn.query(sql1, (err, result) => {
  if (err) {
    console.error("查询数据出现异常:" + err.message)
  }

  console.log(result)
})

// 有查询条件
const sql2 = "select * from talbe_name where col1 > ? and col2 = ? ..."
conn.query(sql2, [col1_val, col2_val, ...], (err, result) => {
  if (err) {
    console.error("查询数据出现异常:" + err.message)
  }

  console.log(result)
})

// 管理连接
conn.end()

注意:通过query()查询,获取的数据结果为一个数组。

插入数据
const mysql = require('mysql2')

// 创建 Connection 实例
const conn = mysql.createConnection({
  host: "127.0.0.1",
  port: 3306,
  database: "db",
  user: "root",
  password: "123456"
})

// 建立连接
conn.connect()

/****************** 插入操作 *********************/
const sql1 = "insert into talbe_name values(?, ?, ...)"
conn.query(sql1, [col1_val, col2_val, ...], (err, data) => {
  if (err) {
    console.error("插入数据出现异常:" + err.message)
  }

  // 判断数据是否插入成功
  if (data.affectedRows !== 1) {
    console.error("插入数据失败")
  }

  console.log("数据插入成功")
})

const sql2 = "insert into (col1, col2, ...) talbe_name values(?, ?, ...)"
conn.query(sql2, [col1_val, col2_val, ...], (err, data) => {
  if (err) {
    console.error("插入数据出现异常:" + err.message)
  }

  // 判断数据是否插入成功
  if (data.affectedRows !== 1) {
    console.error("插入数据失败")
  }

  console.log("数据插入成功")
})

// 此种方式中 query中的第二个参数名必须和数据库中表的名称一样
const sql3 = "insert into talbe_name set ?"
conn.query(sql3, xx, (err, data) => {
  if (err) {
    console.error("插入数据出现异常:" + err.message)
  }

  // 判断数据是否插入成功
  if (data.affectedRows !== 1) {
    console.error("插入数据失败")
  }

  console.log("数据插入成功")
})

// 断开连接
conn.end()
修改数据
const mysql = require('mysql2')

// 创建 Connection 实例
const conn = mysql.createConnection({
  host: "127.0.0.1",
  port: 3306,
  database: "db",
  user: "root",
  password: "123456"
})

// 建立连接
conn.connect()

/****************** 更新操作 *********************/
const sql1 = "updte user talbe_name col1 = ?, col2=?, ... where id = ?)"
conn.query(sql1, [col1_val, col2_val, ..., id_val], (err, data) => {
  if (err) {
    console.error("插入数据出现异常:" + err.message)
  }

  // 判断数据是否插入成功
  if (data.affectedRows !== 1) {
    console.error("插入数据失败")
  }

  console.log("数据插入成功")
})

// 此种方式中 query中的第二个参数名必须和数据库中表的名称一样
const sql3 = "update talbe_name set ? where id = ?"
conn.query(sql3, [xx, id_val], (err, data) => {
  if (err) {
    console.error("更新数据出现异常:" + err.message)
  }

  // 判断数据是否插入成功
  if (data.affectedRows !== 1) {
    console.error("更新数据失败")
  }

  console.log("数据更新成功")
})

// 断开连接
conn.end()
删除数据
const mysql = require('mysql2')

// 创建 Connnection 实例
const conn = mysql.createConnection({
  host: '127.0.0.1',
  port: 3306,
  database: 'db',
  user: 'root',
  password: '123456'
})

// 建立连接
conn.connect()

// 无条件删除
const sql = "delete from talbe_name "
conn.query(sql1, (err, data) => {
  if (err) {
    console.error("删除数据出现异常:" + err.message)
  }
  
  // 判断数据是否删除成功
  if (data.affectedRows > 0) {
    console.error("删除数据失败")
  }
  console.log(result)
})

// 有条件删除
const sql2 = "delete from talbe_name where id = ?"
conn.query(sql2, id_val, (err, data) => {
  if (err) {
    console.error("删除数据出现异常:" + err.message)
  }
  
  // 判断数据是否删除成功
  if (data.affectedRows !== 0) {
    console.error("删除数据失败")
  }
  console.log(result)
})

// 管理连接
conn.end()

问题

连接报ER_NOT_SUPPORTED_AUTH_MODE错误

原因

MySQL 8.0.4开始,MySQL默认身份验证插件从 mysql_native_password改为caching_sha2_password所导致的。

解决方式

解决方式有两种:

  1. 身份验证插件改 mysql_native_password
  2. 安装 mysql2模块

你可能感兴趣的:(node.js,mysql)