thy-util-jdbc-mysql 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.js +86 -0
  2. package/package.json +17 -0
package/index.js ADDED
@@ -0,0 +1,86 @@
1
+ const mysql = require('mysql2')
2
+
3
+ // 通过以下方式引入文件,必须先执行createPromisePool
4
+ // const { createPromisePool, executeQuery, testExecuteQuery } = require('thy-util-jdbc-mysql')
5
+
6
+ let promisePool = null
7
+ /**
8
+ * 创建连接池
9
+ * @param {object} dbconfig - 连接池配置对象。
10
+ */
11
+ function createPromisePool(dbconfig) {
12
+ promisePool = mysql.createPool(dbconfig).promise()
13
+ }
14
+
15
+ /**
16
+ * 执行sql查询
17
+ * @param {string} sql - 文本形式的sql。
18
+ * @param {array} params - 参数。
19
+ * @returns {object} 执行结果。
20
+ */
21
+ async function executeQuery(sql, params) {
22
+ let connection
23
+ try {
24
+ connection = await promisePool.getConnection()
25
+ const [rows, fields] = await connection.execute(sql, params)
26
+
27
+ return {
28
+ success: true,
29
+ data: rows,
30
+ fields: fields,
31
+ message: '查询成功'
32
+ }
33
+ } catch (error) {
34
+ // console.error('数据库查询错误:', error)
35
+ return {
36
+ success: false,
37
+ data: null,
38
+ error: error.message,
39
+ message: '查询失败'
40
+ }
41
+ } finally {
42
+ // 释放连接回连接池
43
+ if (connection) {
44
+ connection.release()
45
+ }
46
+ }
47
+ }
48
+
49
+ // 测试数据库链接
50
+ // (async () => { console.log(await testExecuteQuery()) })()
51
+
52
+ // 也可以用Promise调用
53
+ // testExecuteQuery()
54
+ // .then((message) => {
55
+ // console.log(message)
56
+ // })
57
+ // .catch((error) => {
58
+ // console.error(error)
59
+ // })
60
+
61
+ async function testExecuteQuery() {
62
+ try {
63
+ const result = await executeQuery('SELECT VERSION() as version')
64
+ if (result.success) {
65
+ return ('数据库链接成功,数据库版本: ' + result.data[0].version)
66
+ } else {
67
+ return ('数据库链接失败,请检查配置信息,错误信息: ' + result.error)
68
+ }
69
+ } catch (error) {
70
+ return ('测试过程中发生错误: ' + error)
71
+ } finally {
72
+ // pool.end((err) => { // 关闭连接池
73
+ // if (err) {
74
+ // return ('关闭连接池时出错: ' + err)
75
+ // } else {
76
+ // return ('=== 测试完成,连接池已关闭 ===')
77
+ // }
78
+ // })
79
+ }
80
+ }
81
+
82
+ module.exports = {
83
+ createPromisePool,
84
+ executeQuery,
85
+ testExecuteQuery
86
+ }
package/package.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "thy-util-jdbc-mysql",
3
+ "version": "1.0.0",
4
+ "description": "this is thy-util-jdbc-mysql",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "keywords": [
10
+ "thy-util-jdbc-mysql"
11
+ ],
12
+ "author": "hengyi.tao",
13
+ "license": "ISC",
14
+ "dependencies": {
15
+ "mysql2": "^3.16.1"
16
+ }
17
+ }