简体   繁体   English

如何查看我保存到“MySQL”数据库中的结果?

[英]How can I see the result of what I save into the "MySQL" database?

I have the following function that works fine and saves the new user data into the database:我有以下 function 可以正常工作并将新用户数据保存到数据库中:

  static async create(req: Request, res: Response, next: NextFunction){
    await pool.execute<IUser & RowDataPacket[]>(
      "INSERT INTO users (email, password, admin) VALUES(?,?,?)",
      [req.body.email, req.body.password, req.body.admin])
      .then(() => {
        res.status(200).json(("user created successfully"));
      })
      .catch(err => { console.log(err); next(); });
  }

But when I try to change the following line:但是当我尝试更改以下行时:

await pool.execute<IUser & RowDataPacket[]>(

Like this:像这样:

const user = await pool.execute<IUser & RowDataPacket[]>(

Or change this line:或者更改此行:

.then(() => {

To

.then((user) => { res.send(user);

In none of the cases I can't read the value of user and it's undefined .在任何情况下我都无法读取user的值并且它是undefined Is there a simple way that after I save a user into the database, I get a response with the saved user information inside the database?有没有一种简单的方法可以在我将用户保存到数据库后,得到一个包含数据库中保存的用户信息的响应?

EDIT: The configuration for the database looks like thie below code:编辑:数据库的配置看起来像下面的代码:

import mysql from "mysql2";

const pool =  mysql.createPool(
  {
  host : (process.env.DB_HOST),
  user : (process.env.DB_USER),
  password:  (process.env.DB_PASSWORD ),
  database: (process.env.DB_NAME ),
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
  }).promise();

To use then or await you need a function that return a Promise .要使用 then 或await ,您需要一个返回 Promise 的Promise You can use mysql2/promise你可以使用mysql2/promise

for example:例如:


import mysql, { Connection, MysqlError } from 'mysql2/promise';


async function create(req: Request, res: Response, next: NextFunction) {
  try {
    // create your connection
    const connection = await mysql.createConnection({
      host: 'localhost',
      user: 'user',
      password: 'password',
      database: 'database',
    });

    const userData = [req.body.email, req.body.password, req.body.admin]


  
    const sql = `INSERT INTO users (email, password, admin) VALUES(?,?,?)`;


    // execute the INSERT statement
    const [results] = await connection.query(sql, userData);
    console.log(results.affectedRows);



   
    
  } catch (error) {
    console.error(error);
  }finaly{
    // close the connection in any case
    connection.end();

  }
}





声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM