目录
一 . mysql的基本使用
1. 安装与引入
1. 1 首先要安装包
npm install -s mysql
1.2 引入包
const mysql = require('mysql');
2. 介绍
这是mysql的node.js驱动程序。它是用JavaScript编写的,不需要编译,并且100%获得MIT许可。
这是有关如何使用它的示例:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
connection.end();
在此示例中,我们了解到:
- 在连接上调用的每个方法都按顺序排队并执行。
- 关闭连接是通过使用
end()
该连接来确保在将退出数据包发送到mysql服务器之前执行所有剩余查询的。
3. 建立连接
3.1基本使用:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
connection.end();
常用连接选项:
host
:您要连接的数据库的主机名。(默认值:localhost
)port
:要连接的端口号。(默认值:3306
)user
:要作为身份验证的MySQL用户。password
:该MySQL用户的密码。database
:用于此连接的数据库名称(可选)。
3.2 池连接
创建一个池并直接使用它:
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host : 'example.org',
user : 'bob',
password : 'secret',
database : 'my_db'
});
pool.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
这是pool.getConnection()
-> connection.query()
-> connection.release()
代码流的快捷方式。使用pool.getConnection()
有助于共享连接状态以用于后续查询。这是因为对的两次调用 pool.query()
可能使用两个不同的连接并并行运行。这是基本结构:
var mysql = require('mysql');
var pool = mysql.createPool(...);
pool.getConnection(function(err, connection) {
if (err) throw err; // not connected!
// Use the connection
connection.query('SELECT something FROM sometable', function (error, results, fields) {
// When done with the connection, release it.
connection.release();
// Handle error after the release.
if (error) throw error;
// Don't use the connection here, it has been returned to the pool.
});
});
如果要关闭连接并将其从池中删除,请 connection.destroy()
改用。下次需要该池时,该池将创建一个新连接。
连接是由池延迟创建的。如果将池配置为最多允许100个连接,但仅同时使用5个,则仅建立5个连接。连接也以循环方式循环,连接从池的顶部开始并返回到底部。
从池中检索到先前的连接时,会将ping数据包发送到服务器,以检查连接是否仍然良好。
二. mysql常用指令
1. 查询数据(select)
基本select语句: 一个基本的select语句可分解成三个部分:查找什么数据(select)、从哪里查找(from)、查找的条件是什么(where)。
1.1 基本语法
- select <目标列表达式列表>
- [into 新表名]
- from 表名或视图名
- [where <条件>]
- [group by <分组表达式>]
- [having <条件>]
- [order by <排序表达式>[ASC|DESC]]
1.2 查询指定字段
1. 查询表中所有列
在select语句指定列的位置上使用*号时,表示查询表的所有列。
模板:select * from tb_name;
select * from student
案例:
const express = require('express');
//引入mysql
const mysql = require('mysql');
const app = express();
//处理post请求的参数
app.use(express.urlencoded());
app.use(express.json());
// Create a pool and use it direct
const pool = mysql.createPool({
connectionLimit:10, //连接池的数量
host:'localhost', //访问的地址
user:'root',
password:'root',
database:'students'
})
//RESTfu路由风格
app.get('/students',(req,res) => {
// res.send('获取学生信息');
pool.getConnection(function(err, connection) {
//有错误就抛出错误
if (err) throw err;
console.log('数据库连接成功');
// 没有错误即说明说数据库连接成功,就可以对数据库进行操作了
connection.query('SELECT * FROM student', function (error, results, fields) {
if (error) throw error;
//1. 查询数据结果
res.json(results);
});
});
})
app.listen(3000,()=> {
console.log('server start at 3000 port');
})
2. 查询表中指定的列
查询多列时,列名之间要用逗号隔开。
模板: select <字符型字段>,<字符型字段> ... from tb_name;
//从学生表中选择name和age两列
SELECT name,age FROM student
3. 指定查询结果中的列标题
通过指定列标题(也叫列别名)可使输出结果更容易被人理解。
模板:select <字段> as 别名,<字段2> as 别名2 from bt_name;
//查询结果中使用student代替name
SELECT name as studentname,age FROM student
1.3 查询指定的行
用where子句实现条件查询
通过where子句实现,该子句必须紧跟在From子句之后。 格式为:select * from 表名 where <条件>;
说明:在查询条件中可使用以下运算符或表达式:
- 运算符 运算符标识 比较运算符 <=,<,=,>,>=,!=,<>,!>,!<
- 范围运算符 between... and,not between... and
- 列举运算符 in,not in
- 模糊匹配运算符 like,not like
- 空值运算符 is null,is not null
- 逻辑运算符 and,or,not
1. 使用比较运算
模板:select * from tb_name where <字段> >= n ;
//查询年龄大于20的数据
SELECT * FROM student where age > 20
2. 指定范围
用于指定范围的关键字有两个:between...and和 not between...and。
格式为:select * from tb_name where <字段> [not] between <表达式1> and <表达式2>;
- between关键字之后的是范围的下限(即低值)
- and关键字之后的是范围的上限(即高值) 用于查找字段值在(或不在)指定范围的行
SELECT * FROM student where age between 13 and 24
// 查询age字段的值 在13到24 范围的数据
SELECT * FROM student where age node between 13 and 24
// 查询age字段的值 不在13到24 范围的数据
3. 使用枚举:
使用in关键字可以指定一个值的集合,集合中列出所有可能的值,当表达式的值与集合中的任一元素个匹配时,即返回true,否则返回false。
模板:select * from tb_name where <字段> [not] in (值1,值2,...,值n);
SELECT * FROM student where age in (17,21)
// 查询age字段的值 是23 或者43 的数据
SELECT * FROM student where age not in (18,21)
// 查询age字段的值 不是23 或者43 的数据
4. 使用通配符进行模糊查询:
可用like 子句进行字符串的模糊匹配查询,like子句将返回逻辑值(true或False)。
模板: select * from tb_name where <字段> [not] like <匹配串>;
其含义是:
查找指定字段值与匹配串相匹配的记录。匹配串中通常含有通配符%。 其中: %:代表任意长度(包括0)的字符串
//查询姓名中有欢的数据
SELECT * FROM student where name like "%欢%"
5. 使用null的查询
当需要判定一个表达式的值是否为空值时,使用 is null关键字。 当不使用not时,若表达式的值为空值,则返回true,否则返回false;当使用not时,结果刚好相反。
模板:select * from tb_name where <字段> is [not] null;
SELECT * FROM student where name is null
// 查询username字段为空的数据
SELECT * FROM student where name is not null
// 查询username字段不为空的数据
6. 多重条件查询:
使用逻辑运算符 逻辑运算符and(与:两个条件都要满足)和or(或:满足其中一个条件即可)可用来联接多个查询条件。and的优先级高于or,但若使用括号可以改变优先级。
模板:select * from tb_name where <字段> = 'values' and <字段> > n;
SELECT * FROM student where username like "%欢%" and sex = "女"
// 查询username 字段值包含"欢" 并且 sex字段值为"女"
SELECT * FROM student where username like "%欢%" or age >= 20
// 查询username 字段值包含"欢" 或者 age字段 大于等于 20
1.4 对查询结果排序
order by子句可用于对查询结果按照一个或多个字段的值(或表达式的值)进行升序(ASC)或降序(DESC)排列,默认为升序。 格式:order by {排序表达式[ASC|DESC]}[,...n]; 其中:排序表达式既可以是单个的一个字段,也可以是由字段、函数、常量等组成的表达式,或一个正整数。
模板:select * from tb_name order by <排序表达式> <排序方法>;
//// 将查询的结果按照id 字段的降序排序
SELECT * FROM student where age > 18 order by id DESC
2. 插入数据(insert)
insert into 语句用于向表格中插入新的行:
第二种形式需要指定列名及被插入的值: 模板:insert into tb_name (column1,column2,column3,...) values (value1,value2,value3,...);
INSERT INTO student (username,age,sex,classname) VALUES ("张三",12,"男",[1,3])
插入数据案例:
app.post('/students',(req,res) => {
// res.send('新增学生信息');
console.log(req.body);
let {name,id,birth,age,sex} = req.body;
birth = birth && new Date(birth).getTime();
// console.log(name,id,sex,birth,age);
pool.getConnection(function(err, connection) {
if (err) throw err; // not connected!
connection.query('INSERT INTO student (name,age,sex,birth,id) values (?,?,?,?,?)',[name,age,sex,birth,id] ,function (error, results, fields) {
if (error) throw error;
res.send('数据插入成功');
});
});
})
3. 修改数据(update)
Update 语句用于修改表中的数据。
模板: update tb_name set 列名称 = 新值 where 列名称 = 某值;
UPDATE student SET name = 张三 WHERR id = 003
案例:
app.put('/students/:id',(req,res) => {
// res.send('修改学生信息');
let {id} = req.params;
console.log(id)
let student = req.body
console.log(student)
let data = []
for(let key in student){
data.push(key,student[key])
}
data.push(id)
console.log(data)
// res.send("更新学生信息")
pool.getConnection(function(err, connection) {
// 有报错就抛出报错
if (err) throw err; // not connected!
// 更新数据
connection.query(`UPDATE student SET ?? = ? WHERE id = ?`,data, function (error, results, fields) {
// 查询数据库有错误就抛出错误
// console.log(error)
if (error) throw error;
res.send("数据更新成功")
});
});
})
4. 删除数据
4.1 删除单行数据
delete from tb_name where 列名称 = 某值;
delete from student where id = 1
4.2 删除所有数据
可以在不删除表的情况下删除所有的行。这意味着表的结构、属性和索引都是完整的.
delete * from tb_name 或 delete * from tb_nametb_name;
案例:
app.delete('/students',(req,res) => {
// res.send('删除学生信息');
pool.getConnection(function(err, connection) {
if (err) throw err; // not connected!
connection.query('delete from student where id = 5', function (error, results, fields) {
if (error) throw error;
res.send('数据删除成功')
});
});
})