Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- let { init, exec, sql, transaction } = require('mysqls') // 引入 mysqls 的套件
- var randomstring = require("randomstring") // 引入隨機字串產生的套件
- // mysqls 套件,資料庫連線的初始化設定
- init({
- host: 'localhost',
- user: 'root',
- password: '123456',
- database: 'doudizhu',
- port: 8889,
- })
- /**
- * 目標 - 將doudizhu資料庫中,把t_account資料表中有小明的字眼的帳戶撈出再改為新的nick_name
- * 思路 - 先取出資料->再用for迴圈遍歷(資料總數的查詢)->再更新每筆資料
- * 這裡用 async await 來作異步的執行
- */
- // 將doudizhu資料庫中,在t_account資料表中有小明的字眼的帳戶撈出再改為新值
- async function change_user_nickname(where_name) {
- // 查出過濾後的資料,%where_name% 表示模糊查詢有傳入的參數的where_name關鍵字
- const result = await exec(sql
- .table('t_account')
- .field('unique_id','account_id','nick_name')
- .where({ nick_name: { LIKE: '%'+where_name+'%' } })
- .select())
- // 組合隨機字串+數字
- let randomstr = ''
- let randomnum = ''
- let name = ''
- // 使用上面的result的結果取得長度,進行for的遍歷符合條件的資料列
- for (var i = 0; i < result.length ; i++) {
- // 產生新的字串,length是出現的長度,charset是出現新字串的條件
- randomstr = randomstring.generate({
- length: 6,
- charset: 'abcdefg'
- })
- // 產生新的數字,length是出現的長度,charset是出現新數字的條件
- randomnum = randomstring.generate({
- length: 4,
- charset: '0123456789'
- })
- // 組合字串及數字
- name = randomstr + randomnum
- // update 鏈接式語句的用法
- await exec(sql
- .table('t_account')
- .data({nick_name:name})
- .where({ unique_id:result[i].unique_id})
- .update())
- // console.log('result = ' + '['+i+']'+JSON.stringify(result[i].unique_id))
- }
- // console.log('result count = '+JSON.stringify(result))
- }
- // 'xxx' 表傳入要替換的模糊的查詢關鍵字串
- change_user_nickname('xxx')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement