mysql 数据库
- [1] 首先配置 docker 环境
采用 docker-compose 方法
源码: /test-mysql/docker-compose.yml
version: '3.1'
services:mysql:image: mysqlcommand: --default-authentication-plugin=mysql_native_passwordrestart: alwaysenvironment:MYSQL_ROOT_PASSWORD: exampleports:- 3307:3306adminer:image: adminerrestart: alwaysports:- 8081:8080
运行如下命令生成镜像
docker-compose up
- [2] 打开浏览器 localhost:8081
(1)登录管理页面
(2)创建新数据库 mar-mysql
- [3] 写如下配置文件连接数据库
源码: /test-mysql/mysql2.js
部分代码说明:
(1) 连接数据库
const mysql = require('mysql2/promise')
const config = {host: 'localhost',user: 'root',password: 'example',database: 'mar-mysql'
}// 创建连接
const connection = await mysql.createConnection(config)
(2) 创建表
let ret = await connection.execute(`CREATE TABLE IF NOT EXISTS test(id INT NOT NULL AUTO_INCREMENT,message VARCHAR(45) NULL,PRIMARY KEY (id))`
)
(3) 插入数据
let ret = await connection.execute(`INSERT INTO test (message) VALUE(?)`,['abc']);
(4) 查询
const [rows] = await connection.execute(`
SELECT * FROM test
`)
mysql2.js
(async () => {const mysql = require('mysql2/promise');const cfg = {host: "localhost",user: "root",password: "example", // 修改为你的密码database: "mar-mysql" // 确保数据库存在};// 创建连接const connection = await mysql.createConnection(cfg);// console.log('conn:', connection);// IF NOT EXISTS: 如果不存在就创建// NOT NULL AUTO_INCREMENT: 非空自增// PRIMARY KEY (id): 主键是id// 创建表let ret = await connection.execute(`CREATE TABLE IF NOT EXISTS test(id INT NOT NULL AUTO_INCREMENT,message VARCHAR(45) NULL,PRIMARY KEY (id))`)console.log('ret:', ret);// 插入数据// ret = await connection.execute(`// INSERT INTO test (message) VALUE(?)// `, ['abc']);// console.log('insert:', ret);// 查询const [rows, fields] = await connection.execute(`SELECT * FROM test`);console.log('select', JSON.stringify(rows));})()
执行mysql2
node .\mysql2.js
ORM
- 对象关系映射: Object Relational Mapping
- 目的: 通过使用描述对象和数据库之间的关系的元数据,将面向对象语言程序中的对象自动持续化到关系数据库中.
- 简单说明: 就是使用对象的方式(而非SQL语句)来操作数据库
- 栗子: Sequelize库
Sequelize
- [1] 连接
const Sequelize = require('sequelize')const sequelize = new Sequelize('mar-mysql', 'root', 'example', {host: 'localhost',dialect: 'mysql',operatorAliases: false
})
- [2] 定义模型
const Fruit = sequelize.define('Fruit', {name: { type: Sequelize.STRING(20), allowNull: false },price: { type: Sequelize.FLOAT, allowNull: false },stock: { type: Sequelize.INTEGET, defaultValue: 0 }
})let ret = await Fruit.sync();
- [3] 执行
node .\sequelize
-
[4] 说明: 以对象的方式编写的程序,通过Sequelize库,在运行时自动转换成SQL语句
-
[5] 补充: 往刚才创建的Fruit表中 插入一条数据 banana
let ret = await Fruit.create({name: "香蕉",price: 3.5
});
console.log("banana:", ret);