首页 > 解决方案 > 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 并且不知道为什么会遇到这个问题以及如何解决它

标签: mysqlnode.js

解决方案


我就是这样工作的

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");
  }
}

推荐阅读