javascript - 从 ejs 文件连接到 mysql

标签 javascript mysql node.js

我是 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.

Docs

关于javascript - 从 ejs 文件连接到 mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33998031/

相关文章:

javascript - 为什么我的 SQL 查询执行速度很慢

php - 如何在20行表上显示5条记录?

mysql - 如何在我的数据库中获取具有相同值的用户列表

javascript - 在 Sails.js 中从 MongoDB 获取数据

javascript - 如何在关闭 jQuery Accordion 菜单时折叠所有子菜单

javascript - 如何使用 HTML 计算三 Angular 形的面积

javascript - 尝试在 mousemove 上将 div 移至 "follow"光标,但有延迟

mysql - ON DUPLICATE KEY 查询中的重复项在哪里?

node.js - Blubird 从不点击 .catch 语句

node.js - axios没有检索cookie