新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
node如何連接mysql數(shù)據(jù)庫(kù)
這篇文章主要介紹node如何連接MySQL數(shù)據(jù)庫(kù),文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
成都地區(qū)優(yōu)秀IDC服務(wù)器托管提供商(成都創(chuàng)新互聯(lián)).為客戶提供專業(yè)的成都棕樹(shù)機(jī)房,四川各地服務(wù)器托管,成都棕樹(shù)機(jī)房、多線服務(wù)器托管.托管咨詢專線:18982081108
node使用原生方式,連接mysql數(shù)據(jù)庫(kù)
(async () => { // 鏈接數(shù)據(jù)庫(kù) 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); // 創(chuàng)建一個(gè)新表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); // 新建數(shù)據(jù) ret = await connection.execute(`INSERT INTO tests(message) VALUE(?)`, ['newData']) console.log('新建數(shù)據(jù)', ret); const [rows, fields] = await connection.execute(` SELECT * FROM tests `) console.log('查詢數(shù)據(jù)', rows); })()
使用數(shù)據(jù)庫(kù)中間件(ORM):sequelize連接和操作數(shù)據(jù)庫(kù)
(async () => { // 使用數(shù)據(jù)庫(kù)中間件(ORM):sequelize連接和操作數(shù)據(jù)庫(kù) // 1. 使用Sequelize時(shí),生成的表名會(huì)自動(dòng)加成復(fù)數(shù)s,如fruit->fruits // 2. 自動(dòng)生成主鍵id,自增(缺點(diǎn)是合并新舊數(shù)據(jù)時(shí),id又從1開(kāi)始,會(huì)有重合) 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} }) // 同步數(shù)據(jù)庫(kù) let ret = await Fruit.sync(); // 增加一條數(shù)據(jù) ret = await Fruit.create({ name: 'apple', price: 3.5 }) // 更新數(shù)據(jù) await Fruit.update({ price: 4, }, { where: { name: 'banana', } }) // 查詢 ret = await Fruit.findAll(); // 查詢指定范圍的數(shù)據(jù) const Op = Sequelize.Op; opRet = await Fruit.findAll({ where: { price: { [Op.gt]: 3, [Op.lt]: 5, } } }) console.log('search: '+ JSON.stringify(opRet)); })()
以上是“node如何連接mysql數(shù)據(jù)庫(kù)”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
文章名稱:node如何連接mysql數(shù)據(jù)庫(kù)
文章位置:http://ef60e0e.cn/article/psdogj.html