我是 node.js 的新手,正在尝试学习如何从 ejs 文件连接到 mysql 数据库。我试图搜索示例代码,但该代码无法正常工作。有人可以帮我检查一下吗?谢谢。
function loaddata() {
var sql = require("mysql");
var con = mysql.createConnection({});
con.connect(function (err) {
if (err) {
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
});
con.query('update students set name="sus" where email="smn14@mail.aub.edu"', function (err, rows) {
if (err) throw err;
console.log('Data received from Db:\n');
console.log(rows);
});
con.end(function (err) {
// The connection is terminated gracefully
// Ensures all previously enqueued queries are still
// before sending a COM_QUIT packet to the MySQL server.
});
}
最佳答案
创建连接最差。
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(err, rows,
fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution); });
connection.end();
From this example, you can learn the following:
Every method you invoke on a connection is queued and executed in sequence. Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the
mysql server.
关于javascript - 从 ejs 文件连接到 mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33998031/