createConnection() vs createPool()

brandon·2023년 5월 27일
0

MySQL

목록 보기
1/4

createConnection(): 데이터 베이스로 하나의 connection을 만든다.
하나의 connection 만 필요하고 일일이 관리하려 할때 사용한다.
Connection object를 반환한다.

This method is used to create a single connection to the MySQL database. It returns a new Connection object that represents the individual connection. You typically use createConnection() when you only need a single connection to the database and want to manage it manually.

const mysql = require('mysql2');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'username',
  password: 'password',
  database: 'database_name'
});

connection.connect((err) => {
  if (err) {
    console.error('Error connecting to the database:', err);
    return;
  }
  console.log('Connected to the database.');
  // Perform database queries or operations
});

// Remember to end the connection when you're done
connection.end();

createPool(): 데이터 베이스로 여러개의 connection을 만들때 사용한다.
getConnection() 과 release() 로 연결을 만들고 끊을 수 있다.
end()로 pool을 끝낸다.
Pool object를 반환한다.
pool.promise()를 사용하여 export 하면 .then() 과 .catch() 같은 aynschronous methods 를 사용할 수 있다.

This method is used to create a pool of connections to the MySQL database. A connection pool maintains a set of reusable connections, allowing multiple clients to access the database simultaneously. Instead of creating a single connection, createPool() returns a Pool object that manages the pool of connections. You typically use createPool() when you expect multiple concurrent connections to the database, as it provides better performance and resource management.

const mysql = require('mysql2');

const pool = mysql.createPool({
  host: 'localhost',
  user: 'username',
  password: 'password',
  database: 'database_name',
  connectionLimit: 10 // Maximum number of connections in the pool
});

pool.getConnection((err, connection) => {
  if (err) {
    console.error('Error getting connection from the pool:', err);
    return;
  }
  console.log('Connected to the database.');
  // Perform database queries or operations

  // Release the connection back to the pool when you're done
  connection.release();
});

// Remember to end the pool when your application exits
pool.end();
profile
everything happens for a reason

0개의 댓글