[Nodejs]mysql+promise

mysql+promise ์‚ฌ์šฉ์— ๋Œ€ํ•œ ์ฝ”๋“œ ์ž…๋‹ˆ๋‹ค.
๊ตต์€๊ธ€์”จ ๋ถ€๋ถ„์ด mysql๊ณผ promise๋ฅผ ์‚ฌ์šฉํ•˜๋Š”๋ถ€๋ถ„์ž…๋‹ˆ๋‹ค.
์•„๋ž˜์™€ ๊ฐ™์ด ์‚ฌ์šฉํ•˜์‹œ๋ฉด mysql์ž‘์—…์„ ์ˆœ์„œ๋Œ€๋กœ ์ฒ˜๋ฆฌ ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
rows๋ณ€์ˆ˜ ๋ถ€๋ถ„์ด ์ œ์ผ ์ฒ˜์Œ ์ž‘์—…์ด ๋๋‚˜๋ฉด rows2๋ถ€๋ถ„์˜ ์ž‘์—…์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค.

This is code for using mysql+promise.
The part in bold is the part that uses mysql and promise.
When the rows variable part is finished first, the rows2 part begins.

const rows = await promisePrint(hostname, dbuser, dbpassword, dbname, "username");
const rows2 = await promisePrint(hostname, dbuser, dbpassword, dbname, "username2");

์ „์ฒด์ฝ”๋“œ(full code)

const mysql      = require('mysql2');
const express = require('express');
const dbname = "your_db_name";
const hostname = "localhost";
const dbuser = "your_db_user_name";
const dbpassword = "your_db_password";
const { createServer } = require('http');

// Initialize Express app and HTTP server
const app = express();
const server = createServer(app);

async function  promisePrint(hostname, dbuser, dbpassword, dbname, username) {
    const connection = mysql.createConnection({
        host: hostname,
        user: dbuser,
        password: dbpassword,
        database: dbname
    });

    return new Promise((resolve, reject) => {
        var sql = 'SELECT * FROM video WHERE username = ? ORDER BY id DESC';
        var values = [username];
        connection.query(sql, values, (error, rows) => {
            if (error) {
                reject(error);
            } else {
                resolve(rows);
            }
        });
    }).finally(() => {
        connection.end((err) => {
            if (err) {
                console.error('Error closing the connection:', err);
            } else {
                console.log(` ${username} Connection closed successfully.`);
            }
        });
    });
}


app.get("/", async(req, res) => {

    const connection = mysql.createConnection({
        host     : hostname,
        user     : dbuser,
        password : dbpassword,
        database : dbname
      });
  
      try {
          const rows = await promisePrint(hostname, dbuser, dbpassword, dbname, "username");
          console.log('username:',rows);

      } catch (error) {
          console.error('Error fetching data:', error);
          res.status(500).send('Internal Server Error');
      }

  });

  // Start the server on port 3000 or the port specified in the environment variables
  const port = process.env.PORT || 3000;
  server.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
  });

Leave a Reply