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、在开始访问前,编写一个简单的server.js代码,返回表中的数据。
http://localhost:3000/query/
// 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
推荐操作系统:windows7系统、mysql5.8、DELL G3电脑
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试