微信小程序引用SDK正确操作数据库方法:
0 1 2 3 4 5 6 7 8 9 10 11 |
// 使用wafer-node-sdk导出的mysql访问接口 const { mysql } = require('../qcloud') module.exports = async (ctx, next) => { await mysql('cSessionInfo').select('*').then(res => { ctx.state.code = 0 ctx.state.data = res }).catch(err => { ctx.state.code = -1 throw new Error(err) }) } |
注意:
1、必须使用await,因为数据库获取是异步返回的,此处折腾了好久,刚开始不知道是异步的,总获取不到信息
2、使用await的情况下,必须使用async,否则会报错
**如果不使用await,打印数据库查询结果为如下形式:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
Builder { client: Client_MySQL { config: { client: 'mysql', connection: [Object] }, connectionSettings: { host: 'localhost', port: 3306, user: 'databaseuser', password: 'password', database: 'databasename', charset: 'utf8mb4' }, driver: { createConnection: [Function: createConnection], createPool: [Function: createPool], createPoolCluster: [Function: createPoolCluster], createQuery: [Function: createQuery], escape: [Function: escape], escapeId: [Function: escapeId], format: [Function: format], raw: [Function: raw] }, __cid: 'client0', pool: Pool { _factory: [Object], _inUseObjects: [Array], _draining: false, _waitingClients: [Object], _availableObjects: [Array], _asyncTestObjects: [], _count: 2, _removeIdleTimer: [Object], _removeIdleScheduled: true }, valueForUndefined: Raw { client: [Circular], sql: 'DEFAULT', bindings: undefined, _wrappedBefore: undefined, _wrappedAfter: undefined, _debug: undefined }, _events: { start: [Function], query: [Function], 'query-error': [Function], 'query-response': [Function] }, _eventsCount: 4, makeKnex: [Function: makeKnex] }, and: [Circular], _single: { table: 'test', only: false }, _statements: [ { grouping: 'columns', value: [Array] }, { grouping: 'where', type: 'whereBasic', column: 'id', operator: '=', value: 2, not: false, bool: 'and' } ], _method: 'select', _debug: undefined, _joinFlag: 'inner', _boolFlag: 'and', _notFlag: false } |