Sobes.tech
Junior — Middle

Explain what a PreparedStatement object is and what it is used for in database work.

sobes.tech AI

Answer from AI

PreparedStatement is an object used to execute parameterized SQL queries against a database. In Node.js, when working with databases through libraries (such as mysql2 or pg), prepared statements allow:

  • Enhancing security by preventing SQL injection, as parameters are passed separately from the query text.
  • Improving performance when executing the same query multiple times with different parameters, since the query is compiled once.

Example of usage with mysql2:

const mysql = require('mysql2/promise');

async function example() {
  const connection = await mysql.createConnection({host: 'localhost', user: 'root', database: 'test'});
  const [rows] = await connection.execute('SELECT * FROM users WHERE id = ?', [userId]);
  console.log(rows);
}

Here, ? is a parameter that is replaced with the value from the [userId] array in a safe manner.