mysql - NodeJS:插入 MySQL 错误“无法读取 null 的属性‘查询’”
问题描述
我有两个简单的 js 文件,一个是入口点(main.js),另一个是连接和方法。这是课程
const mysql = require("mysql2/promise");
class MySQLBackend {
constructor() {
this.connection = null;
}
async connect() {
this.connection = await mysql.createConnection({
host: "localhost",
port: 3308,
user: "root",
password: "",
database: "dbname",
});
return this.connection;
}
async disconnect() {
this.connection.end();
}
async insert() {
return this.connection.query(
"insert into coins (value_date, coin_value) values ('2021-03-20 10:12:13', '4.25')"
);
}
async test() {
const connection = this.connect();
if (connection) {
console.log("connected!!"); //prints connected!!
await this.insert();
} else {
throw new Error("Error connecting to mysql");
}
}
}
module.exports = MySQLBackend;
在 main.js 中,这是入口点
const MySQLBackend = require("./services/backend/MySQLBackend");
async function runMySQL() {
const mysqlBackend = new MySQLBackend();
return mysqlBackend.test();
}
runMySQL()
.then((result) => {
console.log(result);
})
.catch((err) => console.error(err));
但我明白了
connected!!
TypeError: Cannot read property 'query' of null
我正在学习 Node 并且不知道为什么会遇到这个问题以及如何解决它
解决方案
我就是这样工作的
async insert() {
return this.connection.query(
"insert into table (field) values ('value')"
);
}
async test() {
*this.connection* = *await* this.connect();
if (this.connection) {
console.log("connected!!");
await this.insert();
} else {
throw new Error("Error connecting to mysql");
}
}
推荐阅读
- centering - Lavaan 中的多级中介,变量居中
- latex - 在使用 LaTeX 学习英语语法中标记主语 (S) 和动词 (V)
- arrays - MongoDB:如何计算键中值的数量
- django - 主键的 django uuid 或 hashid 字段?以及如何在生成的 ID 前加上“cust_”
- ruby - Ruby如何调用函数直到正确的条件?
- vue.js - Nuxt js样式问题
- r - 使用 geom_count (ggplot2, R) 编辑点大小
- python - 如何在Django中转换货币?
- r - 添加具有特定值的列
- bash - YAML azure 管道和模板 - 遍历从主管道传递的字符串中拆分出来的每个值,或者使用 bash 将数组作为输出传递