首頁 > web前端 > js教程 > 主體

實戰學習:聊聊Node.js怎麼操作資料庫

青灯夜游
發布: 2022-12-15 21:14:51
轉載
2669 人瀏覽過

這篇文章分享Node.js服務端實戰,介紹一下Node操作資料庫的方法,希望對大家有幫助!

實戰學習:聊聊Node.js怎麼操作資料庫

本系列是使用node作為伺服器開發的操作過程記錄,記錄一下主要​​的內容並且整理過程的脈絡,以初學者的方式將學習內容記錄下來,從0到1逐步的學習node,教程使用過程中用到的是基於express的node框架。 【相關教學推薦:nodejs影片教學程式設計教學

連線資料庫##
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) //查询语句返回的是数组
  }
})
登入後複製

第一次連接資料庫馬上就報錯了,還能怎麼辦呢,直接谷歌搜吧

ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client
登入後複製

實戰學習:聊聊Node.js怎麼操作資料庫

#大概意思是涉及到一些操作權限的問題,需要我們到資料庫中執行這個語句,如果沒報錯的話大家可以跳過這個步驟。

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '这个地方替换成你的数据库密码';
登入後複製

在mysqlworkbrench中執行一下即可,然後回到我們的程式碼繼續執行連接資料庫的動作

實戰學習:聊聊Node.js怎麼操作資料庫

當輸出這個語句的時候證明已經是連線成功的了

實戰學習:聊聊Node.js怎麼操作資料庫

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)
    }
})
登入後複製

實戰學習:聊聊Node.js怎麼操作資料庫

affectedRows為影響行,影響行數為1說明執行i​​nsert語句成功,所以我們這邊可以修改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')
    }
})
登入後複製

更多node相關知識,請造訪:

nodejs 教學

以上是實戰學習:聊聊Node.js怎麼操作資料庫的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:juejin.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!