Advertisement
Guest User

Untitled

a guest
Apr 20th, 2019
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. let { init, exec, sql, transaction } = require('mysqls') // 引入 mysqls 的套件
  2. var randomstring = require("randomstring") // 引入隨機字串產生的套件
  3.  
  4. // mysqls 套件,資料庫連線的初始化設定
  5. init({
  6. host: 'localhost',
  7. user: 'root',
  8. password: '123456',
  9. database: 'doudizhu',
  10. port: 8889,
  11. })
  12.  
  13. /**
  14. * 目標 - 將doudizhu資料庫中,把t_account資料表中有小明的字眼的帳戶撈出再改為新的nick_name
  15. * 思路 - 先取出資料->再用for迴圈遍歷(資料總數的查詢)->再更新每筆資料
  16. * 這裡用 async await 來作異步的執行
  17. */
  18. // 將doudizhu資料庫中,在t_account資料表中有小明的字眼的帳戶撈出再改為新值
  19. async function change_user_nickname(where_name) {
  20.  
  21. // 查出過濾後的資料,%where_name% 表示模糊查詢有傳入的參數的where_name關鍵字
  22. const result = await exec(sql
  23. .table('t_account')
  24. .field('unique_id','account_id','nick_name')
  25. .where({ nick_name: { LIKE: '%'+where_name+'%' } })
  26. .select())
  27.  
  28. // 組合隨機字串+數字
  29. let randomstr = ''
  30. let randomnum = ''
  31. let name = ''
  32.  
  33. // 使用上面的result的結果取得長度,進行for的遍歷符合條件的資料列
  34. for (var i = 0; i < result.length ; i++) {
  35. // 產生新的字串,length是出現的長度,charset是出現新字串的條件
  36. randomstr = randomstring.generate({
  37. length: 6,
  38. charset: 'abcdefg'
  39. })
  40. // 產生新的數字,length是出現的長度,charset是出現新數字的條件
  41. randomnum = randomstring.generate({
  42. length: 4,
  43. charset: '0123456789'
  44. })
  45. // 組合字串及數字
  46. name = randomstr + randomnum
  47.  
  48. // update 鏈接式語句的用法
  49. await exec(sql
  50. .table('t_account')
  51. .data({nick_name:name})
  52. .where({ unique_id:result[i].unique_id})
  53. .update())
  54.  
  55. // console.log('result = ' + '['+i+']'+JSON.stringify(result[i].unique_id))
  56. }
  57. // console.log('result count = '+JSON.stringify(result))
  58. }
  59. // 'xxx' 表傳入要替換的模糊的查詢關鍵字串
  60. change_user_nickname('xxx')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement