mysql - nodejs访问mysql数据库的最佳实践

标签 mysql node.js

目前我正在运行一个带有 express 的 Node js 后端,以从客户端访问 mysql 数据库。现在我正在重构我的代码,将客户端的“胖”东西也放到 nodejs 后端。 我的第一个想法是保持快速路线:

模块A:

router.get('/getitem/:code',(req, res) => {
let sql = `SELECT * FROM xyz WHERE CODE = ${req.params.code}`;
let query = db.query(sql, (err, result) =>{
  if(err == null){
    console.log(result);
    res.send(result);
  }else{
    console.log("Error by getting item from db: " + err);
    throw err;
  }
 });
});

如果需要,可以通过其他模块的 http 请求访问它:

function geodataByLocationcode(locationcode){
 request({
  method: 'GET',
  url: "http://" + server_connection.host + ":" + server_connection.port + '/getitem/' + locationcode,
  headers: {
    "Content-Type": "application/json"
  }
 },function(error, response, body){
 ....
 }

但这是最好的方法吗? 或者以更直接的方式访问数据库会更好吗 因为请求现在也来自后端?

最佳答案

您可以找到一个很好的示例,了解如何使用 native 驱动程序使用 MySql 和 Node.js(无需任何查询构建器,如 knex 或 ORM,如书架)。

依赖关系:

  • expressjs 4.x
  • mysql2

expressjs 4.x

核心概念是:

示例:https://github.com/Talento90/organization-api/tree/master/organizations-api/src

关于mysql - nodejs访问mysql数据库的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46668183/

相关文章:

mysql - Entity Framework 逆向工程代码优先可以与 MySql 一起使用吗?

mysql - 如何使 SELECT "knows"哪个实体有更多元素?

node.js - 修剪 cloudformation 中的 secret 管理器 ARN

Node.js & Redis & For Loop with bluebird Promises?

mysql - 为什么程序中游标取空?

c++ - 使用嵌入式 mysql C++ 创建触发器

php - 数据库中用户数据更改后如何用php刷新页面?

node.js - ZINTERSTORE 与 node_redis 的动态参数

javascript - 我怎样才能将一个配置对象共享给多个数据

javascript - 将 Node 中收到的 POST 请求转换为 Javascript 对象