0
0
Expressframework~10 mins

Raw queries when needed in Express - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to execute a raw SQL query using Express with a database client.

Express
db.query([1], (err, result) => {
  if (err) throw err;
  res.send(result.rows);
});
Drag options to blanks, or click blank then click option'
Adb.execute('SELECT * FROM users')
BSELECT * FROM users
C"SELECT * FROM users"
Dquery('SELECT * FROM users')
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put the SQL query inside quotes.
Using incorrect method names like execute or query without context.
2fill in blank
medium

Complete the code to safely insert a user name using parameterized raw query to avoid SQL injection.

Express
const sql = 'INSERT INTO users(name) VALUES($1)';
db.query(sql, [[1]], (err, res) => {
  if (err) throw err;
  console.log('User added');
});
Drag options to blanks, or click blank then click option'
AuserName
Busername
Cname
Dreq.body.name
Attempts:
3 left
💡 Hint
Common Mistakes
Passing variable names that are undefined in the context.
Not using parameterized queries and inserting values directly.
3fill in blank
hard

Fix the error in the raw query callback by completing the missing parameter to handle the result.

Express
db.query('SELECT * FROM products', (err, [1]) => {
  if (err) {
    console.error(err);
    return;
  }
  res.json([1].rows);
});
Drag options to blanks, or click blank then click option'
Aresult
Bresponse
Cdata
Doutput
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect parameter names that do not match the result object.
Forgetting to use the result parameter to access rows.
4fill in blank
hard

Fill both blanks to create a raw query that updates a user's email by id using parameters.

Express
const sql = 'UPDATE users SET email = $1 WHERE id = $2';
db.query(sql, [[1], [2]], (err, res) => {
  if (err) throw err;
  res.send('Email updated');
});
Drag options to blanks, or click blank then click option'
Areq.body.email
Breq.params.id
CuserEmail
DuserId
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up the order of parameters.
Using undefined variables instead of request data.
5fill in blank
hard

Fill all three blanks to write a raw query that deletes a user by id and logs the affected row count.

Express
const sql = 'DELETE FROM users WHERE id = $1';
db.query(sql, [[1]], (err, [2]) => {
  if (err) throw err;
  console.log('Deleted rows:', [3].rowCount);
});
Drag options to blanks, or click blank then click option'
Areq.params.userId
Bresult
Cres
Dreq.body.id
Attempts:
3 left
💡 Hint
Common Mistakes
Using request body instead of URL params for id.
Not using the correct result parameter to get rowCount.