escape sql parameter in typescript

To escape SQL parameters in TypeScript, you can use parameterized queries, which use placeholders to represent the parameters in the SQL statement, and then bind the actual values to the placeholders separately. This technique prevents SQL injection attacks by separating SQL code from user input.

Here is an example of preparing a parameterized SQL statement and binding values in TypeScript using the mysql2 library:

index.ts
import mysql from 'mysql2';

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

const name = "John Doe";
const age = 30;

const sql = 'SELECT * FROM users WHERE name = ? AND age = ?'; // parameterized SQL statement
const values = [name, age]; // values to bind to the placeholders

connection.query(sql, values, (error, results, fields) => {
  if (error) throw error;
  console.log(results);
});

connection.end();
493 chars
22 lines

In this example, the SQL statement SELECT * FROM users WHERE name = ? AND age = ? contains two placeholders represented with ? symbols. The values array contains the values that will be bound to the placeholders in the same order as they appear in the SQL statement.

By using parameterized queries and separating SQL code from user input, you can prevent SQL injection attacks and ensure the safety and security of your application.

gistlibby LogSnag