## nodejs连接mysql

想要成为一个全栈工程师,自然需要会后端,那nodejs连接mysql就更不能不会了。

  • 首先安装sql依赖:npm i sql

  • 编写代码连接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const mysql = require('mysql')

// 创建链接对象
const con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123456',
port: '3306',
database: 'myblog'
})

// 开始链接
con.connect()

// 执行 sql 语句
const sql = 'select * from users;'
con.query(sql,(err,result)=> {
if(err){
console.error(err)
return
}
console.log(result)
})

// 关闭链接
con.end()
  • 运行 :node index.js

在这里插入图片描述如果遇到报错: Client does not support authentication protocol requested by server

可看这篇文章:连接MySQL报错:Client does not support authentication protocol requested by server