mysql模块是一个第三方模块,专门用来操作MySQL数据库。 我们可以在npm包中先下载模块才能进行node.js连接操作mysql数据库。
npm包下载方法参考 mysql模块介绍
使用步骤
要想用这个包连接数据库,首先要确保在电脑有mysql(phpstudy 还要启动mysql服务)
一共需要4个步骤:
-
加载 MySQL 模块
-
创建 MySQL 连接对象
-
连接 MySQL 服务器
-
执行SQL语句
// 1. 加载msyql
var mysql = require('mysql');
// 2. 创建连接
var connection = mysql.createConnection({
host : 'localhost', // 你要连接的数据库服务器的地址
port : 3306,// 端口号
user : 'root', // 连接数据库服务器需要的用户名
password : 'root', // 连接数据库服务器需要的密码
database : 'node136' //你要连接的数据库的名字
});
// 3. 连接数据库
connection.connect((err) => {
// 如果有错误对象,表示连接失败
if (err) return console.log('数据库连接失败')
// 没有错误对象提示连接成功
console.log('mysql数据库连接成功')
});
// 4. 执行SQL语句
let sql = 'select id,name,age from student';//想要做不同操作更改不同sql语句即可
connection.query(sql, (err, result) => {
if (err) {
console.log('错误',err)
} else {
console.log(result); // result就是查询结果
}
});
参考地址: https://www.npmjs.com/package/mysql#introduction
写一个真正的接口
目标
基于nodejs 用express + mysql 包 写接口
基于nodejs 用express + mysql 包 写接口,实现学生数据添加。
要求:
接口1
添加学生数据
url: localhost:3000/api/student
method: post
参数格式:普通键值对
- name: 字符串
- age: 数值
测试:postman来测试
接口2
获取所有的学生数据
url: localhost:3000/api/student
method: get
参数:无
测试:postman来测试
思路
- 创建项目serverAPI
- npm init --yes
- 安装包: npm i express mysql
- restful风格
实现添加
sql.js
// 1. 加载msyql
var mysql = require('mysql');
// 2. 创建连接
var connection = mysql.createConnection({
host : 'localhost', // 你要连接的数据库服务器的地址
port : 3306,// 端口号
user : 'root', // 连接数据库服务器需要的用户名
password : 'root', // 连接数据库服务器需要的密码
database : 'node136' //你要连接的数据库的名字
});
// 3. 连接数据库
connection.connect((err) => {
// 如果有错误对象,表示连接失败
if (err) return console.log('数据库连接失败')
// 没有错误对象提示连接成功
console.log('mysql数据库连接成功')
});
module.exports = connection
参考代码
const express = require('express')
const app = express()
app.use(express.urlencoded())
const connection = require('./utils/sql')
app.post('/api/student',(req,res)=>{
console.log(req.body)
// 1. 接收普通键值对的参数
const { name, age } = req.body
// 2. 添加到数据库中
const sql = `insert into student(name, age) values('${name}',${age})`
console.log('要执行的sql', sql)
// connection.query(sql语句,(err, data)=>{
connection.query(sql,(err, data)=>{
if(err) {
console.log(err)
res.json({msg:'添加失败', code: 0})
} else {
console.log(data)
// 返回
res.json({msg:'添加成功', code: 1})
}
})
})
app.get('/api/student',(req,res)=>{
// 返回
res.json({msg:'查询成功', code: 1})
})
app.listen(3000, ()=>{
console.log('接口服务器启动,3000...')
})
实现查询
app.get('/api/student',(req,res)=>{
// 创建sql
// connection.query(sql,(err, data)=> { })
const sql = `select * from student`
connection.query(sql,(err, data)=> {
if(err) {
res.json({msg:'查询失败', code: 0})
} else {
res.json({msg:'查询成功', code: 1,result: data})
}
})
})