node中的MySQL模块

172 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第13天,点击查看活动详情

node中的MySQL模块

mysql模块是一个第三方模块,专门用来操作MySQL数据库。 可以执行增删改查操作

下载MySQL模块

# 注意,安装mysql的文件夹,不能用中文,不能叫mysql(不能和模块同名)# 最好先执行下面这条命令,会帮你提高下载速度
npm config set registry https://registry.npm.taobao.org# 初始化
npm init -y
​
# 执行下面的命令,下载安装mysql
npm i mysql

MySQL使用步骤

# 1. 加载mysql模块
const mysql = require('mysql');
# 2. 创建连接对象(设置连接参数)
const conn = mysql.createConnection({
    // 属性:值
    host: 'localhost',
    user: 'root',
    password: '密码',
    database: '数据库名'
});
​
#3. 连接到MySQL服务器
conn.connect();
​
# 4. 完成查询(增删改查)
conn.query(SQL语句, (err, result) => {
    err: 错误信息
    result: 查询结果
});
​
# 5. 关闭连接,释放资源
conn.end();

查询数据

-- 基本的查询语法、不区分大小写
select 字段,字段,.... from 表名
​
-- 查询所有的字段
SELECT * FROM 表名
​
-- 带条件的查询
SELECT * FROM 表名 [WHERE 条件] [ORDER BY 排序字段[, 排序字段]] LIMIT [开始位置,]长度
​
.....

基本查询

#select  字段名1, 字段名2,....  from  表名 select username,age from student   // 查询  学生表中   的   所有学生的   名字和年龄

全部查询

#select * from 表名select * from student        //查询   学生表中  的    所有信息

带条件的查询

#select 字段 from 表名 where 条件select * from student where id<10   //查询id小于10的学生select * from student where id<20 and sex='女'   //查询id小于20的女学生select * from student where age>=20 and age<=30   //查询年龄大于等于20小于等于30的学生

修改数据

#update  表名   set   字段=值, 字段=值,......  where  修改条件   (不指定修改条件会修改所有的数据)
​
update student set age=20, sex='女' where id=11   //修改id为11的数据
​
update student set age=25, sex='女'   //没有指定条件,全部的数据都会修改

删除数据

#delete  from 表名  where 删除条件  (不指定条件将删除所有数据)
​
delete from student where id=11  //删除一条数据delete from student where id>6  //删除满足条件的数据delete from student  //没有指定条件,删除全部数据

添加数据

#insert into 表名 set 字段=值, 字段=值, ....
​
insert into student set age=30, sex='男', username='李青'