共计 1074 个字符,预计需要花费 3 分钟才能阅读完成。
node 应用原生形式,连贯 mysql 数据库
(async () => {
// 链接数据库
const mysql = require('mysql2/promise'); // npm i mysql2
const cfg = {
host: 'localhost',
user: 'root',
password: ';he%0f_,ljyW',
database: 'izengx',
}
const connection = await mysql.createConnection(cfg);
// 创立一个新表 tests
let ret = await connection.execute(`CREATE TABLE IF NOT EXISTS tests (
id INT NOT NULL AUTO_INCREMENT,
message VARCHAR(45) NULL,
PRIMARY KEY (id)
)`)
console.log('create', ret);
// 新建数据
ret = await connection.execute(`INSERT INTO tests(message) VALUE(?)`, ['newData'])
console.log('新建数据', ret);
const [rows, fields] = await connection.execute(`
SELECT * FROM tests
`)
console.log('查问数据', rows);
})()
应用数据库中间件(ORM):sequelize 连贯和操作数据库
(async () => {const Sequelize = require('sequelize');
const sequelize = new Sequelize('izengx', 'root', ';he%0f_,ljyW', {
host: 'localhost',
dialect: 'mysql',
operatorsAliases: false,
})
const Fruit =sequelize.define('Fruit', {name: {type: Sequelize.STRING(20), allowNull: false,},
price: {type: Sequelize.FLOAT, allowNull: false},
stock: {type: Sequelize.INTEGER, defaultValue: 0}
})
// 同步数据库
let ret = await Fruit.sync();
// 减少一条数据
ret = await Fruit.create({
name: 'banana',
price: 3.5
})
console.log('create', ret);
})()
正文完