Node.js: 使用mysql2读取MariaDB数据
编程
文件夹结构
$ tree -a
.
├── .env
├── config_mariadb.js
├── go_read.sh
└── maria_read.js
使用异步/等待。
#! /usr/bin/node
// ---------------------------------------------------------------
// maria_read.js
//
// Feb/24/2024
//
// ---------------------------------------------------------------
'use strict'
var mysql = require('mysql2/promise')
var config_mariadb = require('./config_mariadb')
// ---------------------------------------------------------------
function compare_by_key_proc (left,right)
{
var aa = left.key
var bb = right.key
var rvalue = 0
if (aa < bb)
{
rvalue = -1
}
else if (aa > bb)
{
rvalue = 1
}
return rvalue
}
// ---------------------------------------------------------------
function sort_key_proc (dict_aa)
{
var array = new Array()
for(var it in dict_aa)
{
array.push({'key':String (it), 'value':dict_aa[it]})
}
array.sort (compare_by_key_proc)
return array
}
// ---------------------------------------------------------------
function dict_display_proc (dict_aa)
{
const array_aa = sort_key_proc (dict_aa)
array_aa.forEach (function(unit_aa,index)
{
const key = unit_aa.key
const value = unit_aa.value
var out_str = key + "\t"
out_str += value["name"] + "\t"
out_str += value["population"] + "\t"
out_str += value["date_mod"]
console.log (out_str)
})
}
// ---------------------------------------------------------------
async function read01 (mysql,host,user,password,data_base)
{
try {
var conn = await mysql.createConnection({
host: host,
user: user,
password: password,
database: data_base
})
const sql_str = 'select * from cities'
const [rows, fields] = await conn.execute(sql_str)
return rows
} catch (ee) {
console.log(ee)
return ''
} finally {
if (conn && conn.connection) {
conn.end()
}
}
}
// ---------------------------------------------------------------
async function main()
{
const [host, user, password, data_base] = config_mariadb.config_mariadb_proc()
const rows = await read01 (mysql,host,user,password,data_base)
var dict_aa = new Object ()
rows.forEach(function(row)
{
dict_aa[row.id] = {"name": row.name,
"population": row.population,
"date_mod": row.date_mod}
})
dict_display_proc (dict_aa)
console.error ("*** 終了 ***")
}
// ---------------------------------------------------------------
console.error ("*** 開始 ***")
main()
// ---------------------------------------------------------------
.env
config_mariadb.py
在这里
Node.js:显示MariaDB的版本
执行命令
export NODE_PATH=/usr/lib/node_modules
./maria_read.js
确认版本
$ node -v
v19.7.0