在使用mysql模块操作mysql数据库之前,必须先对mysql模块进行必要的配置
步骤如下:
const mysql = require('mysql') const db = mysql.createPool({ host: '127.0.0.1', user: 'root', password: '123456', database: 'my_db_01' })
2.测试mysql模块是否正常工作
const mysql = require('mysql') const db = mysql.createPool({ host: '127.0.0.1', user: 'root', password: '123456', database: 'my_db_01' }) db.query('SELECT 1', (err, result) => { if (err) return console.log(err.message); console.log(result); })
const mysql = require('mysql') const db = mysql.createPool({ host: '127.0.0.1', user: 'root', password: '123456', database: 'my_db_01' }) const sqlStr = 'insert into users (username,password) values (?,?)' db.query(sqlStr, ['wgy', '123456'], (err, result) => { if (err) return console.log(err.message); if (result.affectedRows === 1) { console.log('插入成功'); } }) db.query('SELECT * from users', (err, result) => { if (err) return console.log(err.message); console.log(result); }) //演示插入数据的便捷方法 const sqlStr2 = 'insert into users set ?' const user = { username: "哈哈哈", password: "123456" } db.query(sqlStr2, user, (err, result) => { if (err) return console.log(err.message); if (result.affectedRows === 1) { console.log('插入成功'); } })
更新数据,如上同理
更新数据的便捷方式同样与之前一样(传对象属性进入数组)
删除数据
标记删除
标签:const,log,err,4.2,db,result,模块,mysql From: https://www.cnblogs.com/alwaysrun/p/16652827.html