Nodejs中koa2連接mysql的實(shí)現(xiàn)示例
將查詢結(jié)果轉(zhuǎn)為對象或者數(shù)組
在真實(shí)開發(fā)中,實(shí)際上某些查詢結(jié)果應(yīng)該放入到一個對象中
JSON_OBJECT:()中是key-value的形式
SELECT products.id as id, products.title as title, products.price as price, products.score as score, JSON_OBJECT('id', brand.id, 'name', brand.name, 'rank', brand.phoneRank, 'website', brand.website) as brand FROM products LEFT JOIN brand ON products.brand_id = brand.id;
在多對多關(guān)系中,我們希望查詢到的是一個數(shù)組:
- 比如一個學(xué)生的多門課程信息,應(yīng)該是放到一個數(shù)組中的;
- 數(shù)組中存放的是課程信息的一個個對象;
- 這個時候我們要JSON_ARRAYAGG和JSON_OBJECT結(jié)合來使用;
SELECT stu.id, stu.name, stu.age, JSON_ARRAYAGG(JSON_OBJECT('id', cs.id, 'name', cs.name)) as courses FROM students stu LEFT JOIN students_select_courses ssc ON stu.id = ssc.student_id LEFT JOIN courses cs ON ssc.course_id = cs.id GROUP BY stu.id;
mysql2的使用
安裝mysql2:
npm install mysql2
簡單使用:
const mysql = require('mysql2'); // 1.創(chuàng)建數(shù)據(jù)庫連接 const connection = mysql.createConnection({ host: 'localhost', port: 3306, database: 'coderhub', user: 'root', password: 'Coderwhy888.' }); // 2.執(zhí)行SQL語句 const statement = ` SELECT * FROM products WHERE price > 6000; ` connection.query(statement, (err, results, fields) => { console.log(results); });
如果我們想要在拿到數(shù)據(jù)后停止服務(wù),可以在回調(diào)函數(shù)中寫上:
connection.end()
完整代碼:
connection.query(statement, (err, results, fields) => { console.log(results); connection.end(); });
Prepared Statement(預(yù)處理語句)
提高性能:將創(chuàng)建的語句模塊發(fā)送給MySQL,然后MySQL編譯(解析、優(yōu)化、轉(zhuǎn)換)語句模塊,并且存儲
它但是不執(zhí)行,之后我們在真正執(zhí)行時會給?
提供實(shí)際的參數(shù)才會執(zhí)行;就算多次執(zhí)行,也只會編譯一次,所以性能是更高的;
強(qiáng)調(diào):如果再次執(zhí)行該語句,它將會從LRU(Least Recently Used) Cache中獲取獲取,省略了編譯statement的時間來提高性能。
// 2.執(zhí)行SQL語句: 使用 ?來對參數(shù)進(jìn)行占位 const statement = ` SELECT * FROM products WHERE price > ? AND score > ?; ` connection.execute(statement, [6000, 7], (err, results) => { console.log(results); });
Connection Pools(連接池)
前面我們是創(chuàng)建了一個連接(connection),但是如果我們有多個請求的話,該連接很有可能正在被占用,那么我們是否需要每次一個請求都去創(chuàng)建一個新的連接呢?
- 事實(shí)上,mysql2給我們提供了連接池(connection pools);
- 連接池可以在需要的時候自動創(chuàng)建連接,并且創(chuàng)建的連接不會被銷毀,會放到連接池中,后續(xù)可以繼續(xù)使用;
- 我們可以在創(chuàng)建連接池的時候設(shè)置LIMIT,也就是最大創(chuàng)建個數(shù);
判斷是否連接成功
const mysql = require('mysql2'); // 1.創(chuàng)建連接池 const connections = mysql.createPool({ host: 'localhost', port: 3306, database: 'coderhub', user: 'root', password: 'Coderwhy888.', connectionLimit: 10 }); connections.getConnection((err, conn) => { conn.connect((err) => { if(err){ console.log('連接失敗:',err) } else { console.log('數(shù)據(jù)庫連接成功~') } }) })
簡單使用數(shù)據(jù)庫
const mysql = require('mysql2'); // 1.創(chuàng)建連接池 const connections = mysql.createPool({ host: 'localhost', port: 3306, database: 'coderhub', user: 'root', password: 'Coderwhy888.', connectionLimit: 10 }); // 2.使用連接池 const statement = ` SELECT * FROM products WHERE price > ? AND score > ?; ` connections.execute(statement, [6000, 7], (err, results) => { console.log(results); });
Promise方式
const mysql = require('mysql2'); // 1.創(chuàng)建連接池 const connections = mysql.createPool({ host: 'localhost', port: 3306, database: 'coderhub', user: 'root', password: 'Coderwhy888.', connectionLimit: 10 }); // 2.使用連接池 const statement = ` SELECT * FROM products WHERE price > ? AND score > ?; ` connections.promise().execute(statement, [6000, 7]).then(([results,fields]) => { console.log(results); }).catch(err => { console.log(err); });
sequelize
對象關(guān)系映射(ORM):是一種程序設(shè)計(jì)的方案:
- 從效果上來講,它提供了一個可在編程語言中,使用虛擬對象數(shù)據(jù)庫的效果;
Node當(dāng)中的ORM我們通常使用的是sequelize;
- Sequelize是用于Postgres,MySQL,MariaDB,SQLite和Microsoft SQL Server的基于Node.js 的ORM;
- 它支持非常多的功能;
如果我們希望將Sequelize和MySQL一起使用,那么我們需要先安裝兩個東西:
- mysql2:sequelize在操作mysql時使用的是mysql2;
- sequelize:使用它來讓對象映射到表中;
npm install sequelize mysql2
Sequelize的使用
Sequelize的連接數(shù)據(jù)庫:
第一步:創(chuàng)建一個Sequelize的對象,并且指定數(shù)據(jù)庫、用戶名、密碼、數(shù)據(jù)庫類型、主機(jī)地址等;
第二步:測試連接是否成功;
const { Sequelize } = require('sequelize'); const sequelize = new Sequelize('coderhub', 'root', 'Coderwhy888.', { host: 'localhost', dialect: 'mysql'//連接的數(shù)據(jù)庫類型:mysql,mongoose }); sequelize.authenticate().then(() => { console.log("連接數(shù)據(jù)庫成功~"); }).catch(err => { console.log("連接數(shù)據(jù)庫失敗~", err); });
Sequelize的單表操作
const { Sequelize, DataTypes, Model, Op } = require('sequelize'); const sequelize = new Sequelize("coderhub", 'root', 'Coderwhy888.', { host: 'localhost', dialect: 'mysql' }) //1.首先我們需要將數(shù)據(jù)庫中的一張表映射成一個class類 class Product extends Model {} Product.init({ id: { type: DataTypes.INTEGER, primaryKey: true,//主鍵 autoIncrement: true//自動增長 }, title: { type: DataTypes.STRING, allowNotNull: false//是否可以為空 }, price: DataTypes.DOUBLE, score: DataTypes.DOUBLE }, {//與數(shù)據(jù)庫的表進(jìn)行映射的配置 tableName: 'products', createdAt: false, updatedAt: false, sequelize }); //存放操作數(shù)據(jù)庫的代碼 async function queryProducts() { //1.查詢數(shù)據(jù)庫中product表中所有的內(nèi)容 const result1 = await Product.findAll({ where: {//在這里配置條件 price: { [Op.gte]: 5000//意思是價(jià)格大于等于5000 //gte:大于等于,gt:大于,lt:小于,lte:小于等于 } } }); console.log(result1); // 2.插入數(shù)據(jù) const result2 = await Product.create({ title: "三星Nova", price: 8888, score: 5.5 }); console.log(result2); // 3.更新數(shù)據(jù) const result3 = await Product.update({ price: 3688 }, { where: { id: 1 } }); console.log(result3); } queryProducts();//執(zhí)行這個函數(shù)可以實(shí)現(xiàn)對數(shù)據(jù)庫的操作
Sequelize的一對多操作
const { Sequelize, DataTypes, Model, Op } = require('sequelize'); const sequelize = new Sequelize("coderhub", 'root', 'Coderwhy888.', { host: 'localhost', dialect: 'mysql' }); //數(shù)據(jù)庫的第一個表: 主表 class Brand extends Model {}; Brand.init({ id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, name: { type: DataTypes.STRING, allowNotNull: false }, website: DataTypes.STRING, phoneRank: DataTypes.INTEGER }, { tableName: 'brand', createdAt: false, updatedAt: false, sequelize }); //數(shù)據(jù)庫的第二個表:附表 class Product extends Model {} Product.init({ id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, title: { type: DataTypes.STRING, allowNotNull: false }, price: DataTypes.DOUBLE, score: DataTypes.DOUBLE, brandId: { field: 'brand_id', type: DataTypes.INTEGER, references: {//這張表使用了Brand的id作為外鍵 model: Brand,//product這張表使用了Brand這個表,所以product必須放在下面 key: 'id' } } }, { tableName: 'products', createdAt: false, updatedAt: false, sequelize }); // 將兩張表聯(lián)系在一起 Product.belongsTo(Brand, { foreignKey: 'brandId'//外鍵 }); async function queryProducts() { const result = await Product.findAll({ include: { //這里是聯(lián)合查詢:意思是包含別的表的信息 model: Brand } }); console.log(result); } queryProducts();
Sequelize的多對多操作
const { Sequelize, DataTypes, Model, Op } = require('sequelize'); const sequelize = new Sequelize("coderhub", 'root', 'Coderwhy888.', { host: 'localhost', dialect: 'mysql' }); // Student表 class Student extends Model {} Student.init({ id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, name: { type: DataTypes.STRING, allowNotNull: false }, age: DataTypes.INTEGER }, { tableName: 'students', createdAt: false, updatedAt: false, sequelize }); // Course表 class Course extends Model {} Course.init({ id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, name: { type: DataTypes.STRING, allowNotNull: false }, price: DataTypes.DOUBLE }, { tableName: 'courses', createdAt: false, updatedAt: false, sequelize }); // StudentCourse表:關(guān)系表 class StudentCourse extends Model {} StudentCourse.init({ id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, studentId: {//與Student表建立關(guān)系 type: DataTypes.INTEGER, references: { model: Student, key: 'id' }, field: 'student_id' }, courseId: {//與Course表建立關(guān)系 type: DataTypes.INTEGER, references: { model: Course, key: 'id' }, field: 'course_id' } }, { tableName: 'students_select_courses', createdAt: false, updatedAt: false, sequelize }); // 多對多關(guān)系的聯(lián)系:Student StudentCourse Course Student.belongsToMany(Course, { through: StudentCourse, foreignKey: 'studentId',//這里是Student與StudentCourse,所以外鍵是studentId otherKey: 'courseId'//StudentCourse與Course,所以外鍵是courseId }); //與上面類似 Course.belongsToMany(Student, { through: StudentCourse, foreignKey: 'courseId', otherKey: 'studentId' }); async function queryProducts() { const result = await Student.findAll({ include: {//所有學(xué)生的選課情況 model: Course } }); console.log(result); } queryProducts();
到此這篇關(guān)于Nodejs中koa2連接mysql的實(shí)現(xiàn)示例的文章就介紹到這了,更多相關(guān)koa2連接mysql內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 使用nodejs連接mySQL寫接口全過程(增刪改查)
- nodejs+mysql實(shí)現(xiàn)用戶相關(guān)的增刪改查的詳細(xì)操作
- 三分鐘教會你用nodejs操作mysql數(shù)據(jù)庫
- Nodejs?連接?mysql時報(bào)Error:?Cannot?enqueue?Query?after?fatal?error錯誤的處理辦法
- NodeJs操作MYSQL方法詳細(xì)介紹
- nodejs中關(guān)于mysql數(shù)據(jù)庫的操作
- NodeJs+MySQL實(shí)現(xiàn)注冊登錄功能
- nodejs連接mysql數(shù)據(jù)庫及基本知識點(diǎn)詳解
- nodejs實(shí)現(xiàn)的連接MySQL數(shù)據(jù)庫功能示例
- Nodejs連接mysql并實(shí)現(xiàn)增、刪、改、查操作的方法詳解
- NodeJS連接MySQL數(shù)據(jù)庫并進(jìn)行增刪改查操作詳解
相關(guān)文章
淺談Node.js輕量級Web框架Express4.x使用指南
本篇文章主要介紹了淺談Node.js輕量級Web框架Express4.x使用指南,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05Node 使用express-http-proxy 做api網(wǎng)關(guān)的實(shí)現(xiàn)
這篇文章主要介紹了Node 使用express-http-proxy 做api網(wǎng)關(guān)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10Windows7系統(tǒng)下如何安裝nodejs16以上版本
這篇文章主要給大家介紹了關(guān)于Windows7系統(tǒng)下如何安裝nodejs16以上版本的相關(guān)資料,很多時候node.js的版本存在兼容,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-07-07Nodejs+Socket.io實(shí)現(xiàn)通訊實(shí)例代碼
本篇文章主要介紹了Nodejs+Socket.io實(shí)現(xiàn)通訊實(shí)例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02