前言
这篇文章用于介绍node和mysql怎么联用,只介绍常用的curd,因为这工作主要还是后端同学做www
这里不介绍怎么安装mysql和一些mysql的基本语句了,只介绍怎么用node操作mysql,还有一些非常基础的概念
驱动程序
首先,我们要知道,mysql和node是两个东西,mysql是一个数据库,node是一个语言,如果想要在mysql和node间进行操作,就需要用到驱动程序了
驱动程序是连接内存和其他存储介质的桥梁
在这里,mysql驱动程序是连接内存数据和mysql数据的桥梁
常用的mysql驱动程序有
- mysql(这是官方的)
- mysql2(原来叫mysql-native,非官方,但是现在和官方有合作,所以API都差不多了)
这里我们使用mysql2
CURD
直接放代码看看好了
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| const mysql = require("mysql2"); const connection = mysql.createConnection({ host : "localhost", user : "snow", password: "snow", database : "library" });
connection.query("select * from book;", function (err, res) { console.log(res); });
connection.query('SELECT * FROM `book` WHERE `BookId` > ? and Quantity > ?', [1, 7], (err, result) => { console.log(result); });
connection.query("delete from user where username = ?", ['Sakura'],(err, result) => { console.log("删除成功"); console.log(result); })
connection.query('insert into user(username, phone, authority) value (\'Sakura\', \'13184574124\', 0)', (err, res) => { console.log("插入成功"); console.log(res); });
connection.query('insert into user(username, phone, authority) value (?, ?, ?)', ['Sakura', '13184574124', 0], (err, result) => { console.log("插入成功"); console.log(result); });
connection.query("update authority = 1 from user where username = ?", ['Sakura'], (err, result) => { console.log("更新成功", result); })
connection.end();
|
查询返回的是一个对象数组
插入,删除,修改会返回一个对象描述相关的信息
另外,mysql2支持promise,你也可以使用promise的方式查询
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| const mysql = require("mysql2/promise"); (async () => { const connection = await mysql.createConnection({ host : "localhost", user : "snow", password: "snow", database : "library" }); try { let [result] = await connection.query("select * from book;"); console.log(result); }catch (e) { console.log(e); }finally { await connection.end() } })()
|
预处理语句
预处理语句主要有两点好处
这里不做过多介绍,直接看看代码怎么写就行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| const mysql = require("mysql2/promise"); (async () => { const connection = await mysql.createConnection({ host : "localhost", user : "snow", password: "snow", database : "library" }); try { let [result] = await connection.execute("select * from book where quantity > ?", ['1']); console.log(result); }catch (e) { console.log(e); }finally { await connection.end() } })()
|
了解更多:https://my.oschina.net/u/616147/blog/1793442
使用连接池
为什么要使用连接池看这里:https://juejin.cn/post/6844903602939494414,其实和线程池都差不多,简单来说就是为了复用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const mysql = require("mysql2/promise"); const pool = mysql.createPool({ host : "localhost", user : "snow", password: "snow", database : "library", multipleStatements : true }); (async () => { try { let [result] = await pool.execute("select * from book where quantity > ?", ['1']); console.log(result); }catch (e) { console.log(e); } })()
|
后记
orz好水啊,不过康康就行,毕竟我是前端,学的一点node也是做课设还有做一些简单的处理用的