您好,欢迎访问一九零五行业门户网

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 brandfrom 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 coursesfrom students stuleft join students_select_courses ssc on stu.id = ssc.student_idleft join courses cs on ssc.course_id = cs.idgroup 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);});
promise方式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);});
sequelize对象关系映射(orm):是一种程序设计的方案:
从效果上来讲,它提供了一个可在编程语言中,使用虚拟对象数据库的效果;
node当中的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的连接数据库:
第一步:创建一个sequelize的对象,并且指定数据库、用户名、密码、数据库类型、主机地址等;
第二步:测试连接是否成功;
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);});
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();//执行这个函数可以实现对数据库的操作
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();
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表:关系表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 coursestudent.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的详细内容。
其它类似信息

推荐信息