本教學逐步說明如何從 mysql
套件 存取原始 MySQL 連線實例。這對於存取僅在原始用戶端本身中可用的低階 API 非常有用。
注意:許多使用 MySQL 的 Node.js / Sails 應用程式永遠不需要此處描述的低階用法。如果您發現自己遇到了 ORM 的限制,通常會有一個不涉及為底層資料庫編寫程式碼的解決方案。即使如此,如果您只是想使用自訂原生 SQL 查詢,請不要再往下讀了,而是查看
sendNativeQuery()
。此外,在我們繼續之前,請確保您已設定資料儲存區以使用功能正常的 MySQL 資料庫。
若要從 MySQL 套件取得作用中的連線,您可以呼叫已註冊資料儲存區物件 (RDI) 的 .leaseConnection()
方法。
// Get the named datastore
var rdi = sails.getDatastore('default');
// Get the datastore configured for a specific model
var rdi = Product.getDatastore();
leaseConnection()
方法以取得作用中的連線rdi.leaseConnection(function(connection, proceed) {
db.query('SELECT * from `user`;', function(err, results, fields) {
if (err) {
return proceed(err);
}
proceed(undefined, results);
});
}, function(err, results) {
// Handle results here after the connection has been closed
})
若要在 Sails 應用程式中取得對低階驅動程式和 MySQL 套件的存取權,您可以從已註冊的資料儲存區物件 (RDI) 中取得它們。
// Get the named datastore
var rdi = sails.getDatastore('default');
// Get the datastore configured for a specific model
var rdi = Product.getDatastore();
var mysql = rdi.driver.mysql;
// Get the named datastore
var rdi = sails.getDatastore('default');
// Grab the MySQL module from the datastore instance
var mysql = rdi.driver.mysql;
// Create a new connection
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'password',
database: 'example_database'
});
// Make a query and pipe the results
connection.query('SELECT * FROM posts')
.stream({highWaterMark: 5})
.pipe(...);