MySQL
npm i mysql
建立連結
import * as mysql from "mysql";
const connection = mysql.createConntection({
host: "url",
user: "user",
password: "password",
database: "database"
})
Query
// 接續上例
connection.query(
'SELECT "bar" AS first_field, "foo" AS second_field',
(err: null | MysqlError, result: any, fields: FieldInfo[Cd2]) => {
console.log(result);
connection.end();
}
)
稍微安全一點的 query(query: string, values: any, cb?: (err) => void)
// 接續上例
connection.query(
'INSERT INTO test (content) VALUES (?)', 'hello world!!'
)
使用 Event 避免 Blocking
使用 row 事件, 減少每次 event loop 佔用的時間, 讓資源回歸 main-thread
// 接續 “建立連結” 的例子
const query = connection.quer('SELECT "bar" AS first_field, "foo" AS second_field');
query.on("result", row => {
// NOTE: 每個 event-loop 只處理一個 row, 以減少 blocking 的時長
console.log(`Content of id ${row.id} is ${row.content}`);
});