关于mysql:Node-连接-MySql

7次阅读

共计 1650 个字符,预计需要花费 5 分钟才能阅读完成。

引子

尝试应用 Node 连贯 MySql 数据库。

  • Origin
  • My GitHub

装置

零碎:macOS Catalina 10.15.7

MySql

应用工具 Homebrew

# 搜寻看下有没有
brew search mysql
# 查看下相干信息,是不是想要的
brew info mysql
# 装置
brew install mysql

这个时候要留神装置之后的提示信息:

  • 版本 8.0.22。
  • 装置的 MySql,没有设置明码,要想更平安,运行命令:mysql_secure_installation
  • MySql 默认配置只容许从本地连接。
  • 想要连贯,运行命令:mysql -uroot
  • 启动命令:brew services start mysql,如果不想要后盾运行服务,运行命令:mysql.server start

执行 mysql_secure_installation 会提醒各种相干的设置,比方明码,是否禁止近程 root 登录,移除测试表等等。

执行 mysql -uroot 时,呈现上面的提醒:

ERROR 1045 (28000): Access denied for user ‘root’@’localhost’ (using password: NO)

依照官网上输出的指令 mysql -u root -p,提醒输出明码,输出 123456 就进入了,网上看有些状况下须要重置明码。

其它命令

  • 查看运行状态:mysql.server status;
  • 敞开:mysql.server stop

MySQL Workbench

官网提供了可视化工具,能够在这里下载,本次应用的版本是 mysql-workbench-community-8.0.22-macos-x86_64。

应用工具连贯本都数据库时,须要填写端口,用命令的形式登录后查问端口:

mysql> show global variables like 'port';

该工具默认显示的端口是 3306。第一次的连贯的时候,会弹窗提醒输出明码。

Node

装置 Node 参考这里。

连贯数据库

在 npm 上能够搜寻连贯 mysql 的库,这里以 mysql 联合 koa 作为示例。

// db.js 文件,次要用来连贯数据库
const mysql = require('mysql');

const client = (sql) => {return new Promise((resolve) => {
  const connection = mysql.createConnection({
    host: 'localhost',
    port: 3306,
    user: 'root', // 用户名
    password: '123456', // 明码
    database: 'test', // 库名称
  });

  connection.connect();

  connection.query(sql, function (error, results, fields) {if (error) throw error;
    resolve(results)
  });

  connection.end();})
}
// server.js 开启服务
const Koa = require('koa');
const cors = require('@koa/cors'); // 解决本地申请跨域问题
const app = new Koa();
const sqlConnect = require('./db');

app.use(cors())

// response
app.use(async ctx => {
  const sql = 'SELECT * FROM table_name'; // table_name 为库中表的名称
  const list = await sqlConnect(sql);
  console.log('list', list)
  ctx.body = list;
});

app.listen(3000);
console.log('server is running at http://localhost:3000')

失常启动后,前端页面申请一下 http://localhost:3000 就能够看到成果。

参考资料

  • node
  • mysql
  • koa
  • MySQL command index
正文完
 0