connection.query('SELECT * FROM todos', (error, todos, fields) => { if (error) { console.error('An error occurred while executing the query') throw error } console.log(todos) })
您可以傳入需要自動轉義的值:
1 2 3 4 5 6 7 8
const id = 223 connection.query('SELECT * FROM todos WHERE id = ?', [id], (error, todos, fields) => { if (error) { console.error('An error occurred while executing the query') throw error } console.log(todos) })
若要傳入多個值,只需將更多元素放入作為第二個參數傳遞的數組中:
1 2 3 4 5 6 7 8 9
const id = 223 const author = 'Flavio' connection.query('SELECT * FROM todos WHERE id = ? AND author = ?', [id, author], (error, todos, fields) => { if (error) { console.error('An error occurred while executing the query') throw error } console.log(todos) })
執行 INSERT 查詢
您可以傳入一個對象:
1 2 3 4 5 6 7 8 9 10
const todo = { thing: 'Buy the milk', author: 'Flavio' } connection.query('INSERT INTO todos SET ?', todo, (error, results, fields) => { if (error) { console.error('An error occurred while executing the query') throw error } })
const todo = { thing: 'Buy the milk', author: 'Flavio' } connection.query('INSERT INTO todos SET ?', todo, (error, results, fields) => { if (error) { console.error('An error occurred while executing the query') throw error } const id = results.resultId console.log(id) })