• 技术文章 >数据库 >MySQL

    mysql模块如何使用

    小妮浅浅小妮浅浅2021-08-28 09:32:47原创3351

    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电脑

    专题推荐:mysql模块
    品易云
    上一篇:mysql instr条件查询的实现 下一篇:mysql服务器端的组件

    相关文章推荐

    • mysql间歇锁是什么• mysql间歇锁的特性分析• mysql临键锁是什么• mysql整数类型的介绍• mysql浮点类型是什么• mysql位类型如何理解• mysql中有哪些字符串类型• mysql中enum类型是什么• mysql中set类型如何理解• mysql instr条件查询的实现

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网