本篇文章和大家聊聊node連接mysql數據庫的方法。有一定的參考價值,有需要的朋友可以參考一下,希望對大家有所幫助。
相關:《node js教程》
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 () => { // 使用數據庫中間件(ORM):sequelize連接和操作數據庫 // 1. 使用Sequelize時,生成的表名會自動加成復數s,如fruit->fruits // 2. 自動生成主鍵id,自增(缺點是合并新舊數據時,id又從1開始,會有重合)EGER, defaultValue: 0} }) // 同步數據庫 let ret = await Fruit.sync(); // 增加一條數據 ret = await Fruit.create({ name: 'apple', price: 3.5 }) // 更新數據 await Fruit.update({ price: 4, }, { where: { name: 'banana', } }) // 查詢 ret = await Fruit.findAll(); // 查詢指定范圍的數據 const Op = Sequelize.Op; opRet = await Fruit.findAll({ where: { price: { [Op.gt]: 3, [Op.lt]: 5, } } }) console.log('search: '+ JSON.stringify(opRet)); })()