Nodejs中koa2怎麼連接mysql
將查詢結果轉為物件或陣列
在真實開發中,實際上某些查詢結果應該放入到一個物件中
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;
在多對多關係中,我們希望查詢到的是一個陣列:
例如一個學生的多門課程訊息,應該是放到一個陣列中的;
陣列中存放的是課程資訊的一個物件;
這時候我們要JSON_ARRAYAGG和JSON_OBJECT結合來使用;
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.创建数据库连接 const connection = mysql.createConnection({ host: 'localhost', port: 3306, database: 'coderhub', user: 'root', password: 'Coderwhy888.' }); // 2.执行SQL语句 const statement = ` SELECT * FROM products WHERE price > 6000; ` connection.query(statement, (err, results, fields) => { console.log(results); });
如果我們想要在拿到資料後停止服務,可以在回呼函數中寫上:
connection.end()
完整程式碼:
connection.query(statement, (err, results, fields) => { console.log(results); connection.end(); });
Prepared Statement(預處理語句)
提高效能:將建立的語句模組傳送給MySQL,然後MySQL編譯(解析、最佳化、轉換)語句模組,並且儲存
它但是不執行,之後我們在真正執行時會給?
提供實際的參數才會執行;就算多次執行,也只會編譯一次,所以效能是更高的;
強調:如果再次執行該語句,它將會從LRU(Least Recently Used) Cache中獲取獲取,省略了編譯statement的時間來提高效能。
// 2.执行SQL语句: 使用 ?来对参数进行占位 const statement = ` SELECT * FROM products WHERE price > ? AND score > ?; ` connection.execute(statement, [6000, 7], (err, results) => { console.log(results); });
Connection Pools(連接池)
前面我們是創建了一個連接(connection),但是如果我們有多個請求的話,該連接很有可能正在被佔用,那麼我們是否需要每次一個請求都去建立一個新的連線呢?
事實上,mysql2為我們提供了連接池(connection pools);
連接池可以在需要的時候自動建立連接,且所建立的連線不會被銷毀,會放到連線池中,後續可以繼續使用;
我們可以在建立連線池的時候設定LIMIT,也就是最大建立個數;
判斷是否連接成功
const mysql = require('mysql2'); // 1.创建连接池 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('数据库连接成功~') } }) })
簡單使用資料庫##
const mysql = require('mysql2'); // 1.创建连接池 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); });
const mysql = require('mysql2');
// 1.创建连接池
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);
});
登入後複製
sequelizeconst mysql = require('mysql2'); // 1.创建连接池 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); });
物件關係映射(ORM):是一種程式設計的方案:
- 從效果來講,它提供了一個可在程式語言中,
使用虛擬物件資料庫的效果;
- Sequelize是用於Postgres,MySQL,MariaDB,SQLite和Microsoft SQL Server的基於Node.js 的ORM;
- 它支援非常多的功能;
- mysql2:sequelize在操作mysql時使用的是mysql2;
- sequelize:使用它來讓物件對應到表中;
npm install sequelize mysql2
const { Sequelize } = require('sequelize'); const sequelize = new Sequelize('coderhub', 'root', 'Coderwhy888.', { host: 'localhost', dialect: 'mysql'//连接的数据库类型:mysql,mongoose }); sequelize.authenticate().then(() => { console.log("连接数据库成功~"); }).catch(err => { console.log("连接数据库失败~", err); });
const { Sequelize, DataTypes, Model, Op } = require('sequelize');
const sequelize = new Sequelize("coderhub", 'root', 'Coderwhy888.', {
host: 'localhost',
dialect: 'mysql'
})
//1.首先我们需要将数据库中的一张表映射成一个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
}, {//与数据库的表进行映射的配置
tableName: 'products',
createdAt: false,
updatedAt: false,
sequelize
});
//存放操作数据库的代码
async function queryProducts() {
//1.查询数据库中product表中所有的内容
const result1 = await Product.findAll({
where: {//在这里配置条件
price: {
[Op.gte]: 5000//意思是价格大于等于5000
//gte:大于等于,gt:大于,lt:小于,lte:小于等于
}
}
});
console.log(result1);
// 2.插入数据
const result2 = await Product.create({
title: "三星Nova",
price: 8888,
score: 5.5
});
console.log(result2);
// 3.更新数据
const result3 = await Product.update({
price: 3688
}, {
where: {
id: 1
}
});
console.log(result3);
}
queryProducts();//执行这个函数可以实现对数据库的操作
登入後複製
Sequelize的一對多操作const { Sequelize, DataTypes, Model, Op } = require('sequelize'); const sequelize = new Sequelize("coderhub", 'root', 'Coderwhy888.', { host: 'localhost', dialect: 'mysql' }) //1.首先我们需要将数据库中的一张表映射成一个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 }, {//与数据库的表进行映射的配置 tableName: 'products', createdAt: false, updatedAt: false, sequelize }); //存放操作数据库的代码 async function queryProducts() { //1.查询数据库中product表中所有的内容 const result1 = await Product.findAll({ where: {//在这里配置条件 price: { [Op.gte]: 5000//意思是价格大于等于5000 //gte:大于等于,gt:大于,lt:小于,lte:小于等于 } } }); console.log(result1); // 2.插入数据 const result2 = await Product.create({ title: "三星Nova", price: 8888, score: 5.5 }); console.log(result2); // 3.更新数据 const result3 = await Product.update({ price: 3688 }, { where: { id: 1 } }); console.log(result3); } queryProducts();//执行这个函数可以实现对数据库的操作
const { Sequelize, DataTypes, Model, Op } = require('sequelize');
const sequelize = new Sequelize("coderhub", 'root', 'Coderwhy888.', {
host: 'localhost',
dialect: 'mysql'
});
//数据库的第一个表: 主表
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
});
//数据库的第二个表:附表
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
});
// 将两张表联系在一起
Product.belongsTo(Brand, {
foreignKey: 'brandId'//外键
});
async function queryProducts() {
const result = await Product.findAll({
include: { //这里是联合查询:意思是包含别的表的信息
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' }); //数据库的第一个表: 主表 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 }); //数据库的第二个表:附表 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 }); // 将两张表联系在一起 Product.belongsTo(Brand, { foreignKey: 'brandId'//外键 }); async function queryProducts() { const result = await Product.findAll({ include: { //这里是联合查询:意思是包含别的表的信息 model: Brand } }); console.log(result); } queryProducts();
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表:关系表
class StudentCourse extends Model {}
StudentCourse.init({
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
studentId: {//与Student表建立关系
type: DataTypes.INTEGER,
references: {
model: Student,
key: 'id'
},
field: 'student_id'
},
courseId: {//与Course表建立关系
type: DataTypes.INTEGER,
references: {
model: Course,
key: 'id'
},
field: 'course_id'
}
}, {
tableName: 'students_select_courses',
createdAt: false,
updatedAt: false,
sequelize
});
// 多对多关系的联系: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: {//所有学生的选课情况
model: Course
}
});
console.log(result);
}
queryProducts();
登入後複製
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表:关系表 class StudentCourse extends Model {} StudentCourse.init({ id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, studentId: {//与Student表建立关系 type: DataTypes.INTEGER, references: { model: Student, key: 'id' }, field: 'student_id' }, courseId: {//与Course表建立关系 type: DataTypes.INTEGER, references: { model: Course, key: 'id' }, field: 'course_id' } }, { tableName: 'students_select_courses', createdAt: false, updatedAt: false, sequelize }); // 多对多关系的联系: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: {//所有学生的选课情况 model: Course } }); console.log(result); } queryProducts();
以上是Nodejs中koa2怎麼連接mysql的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Laravel 是一款 PHP 框架,用於輕鬆構建 Web 應用程序。它提供一系列強大的功能,包括:安裝: 使用 Composer 全局安裝 Laravel CLI,並在項目目錄中創建應用程序。路由: 在 routes/web.php 中定義 URL 和處理函數之間的關係。視圖: 在 resources/views 中創建視圖以呈現應用程序的界面。數據庫集成: 提供與 MySQL 等數據庫的開箱即用集成,並使用遷移來創建和修改表。模型和控制器: 模型表示數據庫實體,控制器處理 HTTP 請求。

MySQL和phpMyAdmin是強大的數據庫管理工具。 1)MySQL用於創建數據庫和表、執行DML和SQL查詢。 2)phpMyAdmin提供直觀界面進行數據庫管理、表結構管理、數據操作和用戶權限管理。

MySQL与其他编程语言相比,主要用于存储和管理数据,而其他语言如Python、Java、C 则用于逻辑处理和应用开发。MySQL以其高性能、可扩展性和跨平台支持著称,适合数据管理需求,而其他语言在各自领域如数据分析、企业应用和系统编程中各有优势。

在開發一個小型應用時,我遇到了一個棘手的問題:需要快速集成一個輕量級的數據庫操作庫。嘗試了多個庫後,我發現它們要么功能過多,要么兼容性不佳。最終,我找到了minii/db,這是一個基於Yii2的簡化版本,完美地解決了我的問題。

文章摘要:本文提供了詳細分步說明,指導讀者如何輕鬆安裝 Laravel 框架。 Laravel 是一個功能強大的 PHP 框架,它 упростил 和加快了 web 應用程序的開發過程。本教程涵蓋了從系統要求到配置數據庫和設置路由等各個方面的安裝過程。通過遵循這些步驟,讀者可以快速高效地為他們的 Laravel 項目打下堅實的基礎。

在使用Thelia開發電商網站時,我遇到了一個棘手的問題:MySQL模式設置不當,導致某些功能無法正常運行。經過一番探索,我找到了一個名為TheliaMySQLModesChecker的模塊,它能夠自動修復Thelia所需的MySQL模式,徹底解決了我的困擾。

MySQL通過表結構和SQL查詢高效管理結構化數據,並通過外鍵實現表間關係。 1.創建表時定義數據格式和類型。 2.使用外鍵建立表間關係。 3.通過索引和查詢優化提高性能。 4.定期備份和監控數據庫確保數據安全和性能優化。

MySQL是一個開源的關係型數據庫管理系統,廣泛應用於Web開發。它的關鍵特性包括:1.支持多種存儲引擎,如InnoDB和MyISAM,適用於不同場景;2.提供主從復制功能,利於負載均衡和數據備份;3.通過查詢優化和索引使用提高查詢效率。
