Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Node 连接 MySql #98

Open
XXHolic opened this issue Jan 16, 2021 · 0 comments
Open

Node 连接 MySql #98

XXHolic opened this issue Jan 16, 2021 · 0 comments

Comments

@XXHolic
Copy link
Owner

XXHolic commented Jan 16, 2021

引子

尝试使用 Node 连接 MySql 数据库。

安装

系统:macOS Catalina 10.15.7

MySql

使用工具 Homebrew

# 搜索看下有没有
brew search mysql
# 查看下相关信息,是不是想要的
brew info mysql
# 安装
brew install mysql

84-mysql-install

这个时候要注意安装之后的提示信息:

  • 版本 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 就可以看到效果。

参考资料

🗑️

进击的巨人最终季,在第 5 集里面终于把整体的故事背景讲了出来,过了这么久才揭露出来,真是藏了好久。前期的故事讲述的皇室,让人感觉建立城墙的最开始的人是思想迂腐顽固的反派,现在倒好了,反而是真正的和平爱好者。

84-poster

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant