这篇文章主要讲解了“mysql模块的使用方法”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“mysql模块的使用方法”吧!
1、在使用之前,创建一个名为demo的数据库,同时定义一个名为demo_tabel的表操作log。
C:\Users\James>mysql -u root -p
Enter password: **********
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 8.0.16 MySQL Community Server - GPL
Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> create database demo;
Query OK, 1 row affected (0.12 sec)
mysql> create table demo_tabel
-> (
-> id int(11),
-> name varchar(30),
-> sex varchar(4)
-> );
Query OK, 0 rows affected (0.49 sec)
mysql> show tables;
+----------------+
| Tables_in_demo |
+----------------+
| demo_table |
+----------------+
1 row in set (0.02 sec)
mysql>
2、在开始访问http://localhost:3000/query/前,编写一个简单的server.js代码,返回表中的数据。
// server.js
const Koa = require('koa');
const app = new Koa();
const mysql = require('mysql')
const Router = require('koa-router')
/*
一般情况下操作数据库是很复杂的读写过程,不只是一个会话,
如果直接用会话操作,就需要每次会话都要配置连接参数。
因此需要连接池管理会话。
*/
const pool = mysql.createPool({
host: 'localhost', // 数据库地址
user: 'root', // 登录数据的用户名
password: 'helloworld', // 密码
database: 'demo' // 所用的数据库
})
const port = 3000
const hostName = '127.0.0.1'
const router = new Router();
const query = (sql, values) => {
return new Promise((resolve, reject) => {
pool.getConnection((error, connection) => {
connection.query(sql,values, (error, results) => {
if(error) throw error
connection.release()
resolve(results)
})
})
})
}
router.get('/', async (ctx, next) => {
ctx.res.type = 'application/json'
ctx.body = await query('select * from demo_table')
});
app
.use(router.routes())
.use(router.allowedMethods());
app.listen(port, hostName);
console.log(`http://${hostName}:${port}`)
感谢各位的阅读,以上就是“mysql模块的使用方法”的内容了,经过本文的学习后,相信大家对mysql模块的使用方法这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
亿速云「云数据库 MySQL」免部署即开即用,比自行安装部署数据库高出1倍以上的性能,双节点冗余防止单节点故障,数据自动定期备份随时恢复。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://www.py.cn/db/mysql/31695.html