资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

mysql模块的使用方法

这篇文章主要讲解了“MySQL模块的使用方法”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“mysql模块的使用方法”吧!

我们提供的服务有:网站建设、成都网站制作、微信公众号开发、网站优化、网站认证、慈利ssl等。为上1000+企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的慈利网站制作公司

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模块的使用方法
网页URL:http://cdkjz.cn/article/jsposo.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220