本篇文章分享Node.js服務(wù)端實戰(zhàn),介紹一下Node操作數(shù)據(jù)庫的方法,希望對大家有所幫助!
node.js極速入門課程:進入學習
本系列是使用node作為服務(wù)器開發(fā)的操作過程記錄,記錄一下主要的內(nèi)容并且整理過程的脈絡(luò),以初學者的方式將學習內(nèi)容記錄下來,從0到1逐步的學習node,教程使用過程中用到的是基于express的node框架?!鞠嚓P(guān)教程推薦:nodejs視頻教程、編程教學】
連接數(shù)據(jù)庫
const mysql = require('mysql') const db = mysql.createPool({ host: 'localhost', user: 'root', password: '123123123', database: 'test', insecureAuth : true }) const sql = `select * from new_table` db.query(sql, (err, results) => { // console.log(err) if(err){ console.log(err.message) }else{ console.log(results) //查詢語句返回的是數(shù)組 } })
登錄后復制
第一次連接數(shù)據(jù)庫馬上就報錯了,還能怎么辦呢,直接谷歌搜吧
ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client
登錄后復制
大概意思是涉及到一些操作權(quán)限的問題,需要我們到數(shù)據(jù)庫中執(zhí)行這個語句,如果沒報錯的話大家可以跳過這個步驟。
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '這個地方替換成你的數(shù)據(jù)庫密碼';
登錄后復制
在mysqlworkbrench中執(zhí)行一下即可,然后回到我們的代碼中繼續(xù)執(zhí)行連接數(shù)據(jù)庫的操作
當輸出這個語句的時候證明已經(jīng)是連接成功的了
insert語句
const obj = { name:'xiaoma', password:'666666' } const insertSql = `insert into new_table (name,password) values (?,?)` db.query(insertSql,[obj.name,obj.password],(err,res)=>{ if(err){ console.log(err.message) }else{ console.log(res) } })
登錄后復制
affectedRows為影響行,影響行數(shù)為1說明執(zhí)行insert語句成功,所以我們這邊可以修改一下insert成功的判斷
if(res.affectedRows == 1){ console.log('insert success') }
登錄后復制
簡化新增sql
const obj = { name:'xiaoma', password:'123123' } const insertSql = `insert into new_table SET ?` db.query(insertSql,obj,(err,res)=>{ if(err){ console.log(err.message) } if(res.affectedRows == 1){ console.log('insert success') } })
登錄后復制
update語句
const updateSql = `Update new_table set name=? ,password=? where id=?` // const insertSql = `insert into new_table SET ?` db.query(updateSql,[obj.name,obj.password,obj.id],(err,res)=>{ if(err){ console.log(err.message) } if(res.affectedRows == 1){ console.log('insert success') } }) //簡化寫法 const updateSql = `Update new_table set ? where id=?` db.query(updateSql,[obj,obj.id],(err,res)=>{ })
登錄后復制
delete語句
const updateSql = `delete from new_table where id=?` db.query(updateSql,5,(err,res)=>{ if(err){ console.log(err.message) } if(res.affectedRows == 1){ console.log('insert success') } })
登錄后復制