【问题标题】:Inserting to MySQL using variable from two-step (Node.js)使用两步中的变量插入 MySQL (Node.js)
【发布时间】:2015-10-27 09:26:35
【问题描述】:

我想使用这段代码在 mysql 中存储 2 行(要存储的变量来自 exec):

#!/usr/bin/node
var mysql = require("mysql");

var tempId1 = '28-000006140194';
var tempId2 = '28-000006280f8c'; 

// First you need to create a connection to the db
var con = mysql.createConnection({
  host: "localhost",
  user: "xxx",
  password: "xxx",
  database: "xxx"
});


con.connect(function(err){
  if(err){
    console.log('Error connecting to Db');
    return;
  }
  console.log('Connection established');
});

var TwoStep = require("two-step");
var exec, start;
exec = require('child_process').exec;
start = function() {
  TwoStep(
    function() {
      exec("cat /sys/bus/w1/devices/" + tempId1 + "/w1_slave | grep t= | cut -f2 -d= | awk '{print $1/1000}'", this.val("t1"));
      exec("cat /sys/bus/w1/devices/" + tempId2 + "/w1_slave | grep t= | cut -f2 -d= | awk '{print $1/1000}'", this.val("t2"));
    },
    function(err, t1, t2) {
      var temp1 = parseFloat(t1).toFixed(2);
      var temp2 = parseFloat(t2).toFixed(2);

      var storeTemp1 = { tid: 1, temp: temp1 };
      var storeTemp1 = { tid: 2, temp: temp2 };

      con.query('INSERT INTO temperatures SET ?', storeTemp1, function(err,res){
        if(err) throw err;

        console.log('Last insert ID:', res.insertId);
      });

      con.query('INSERT INTO temperatures SET ?', storeTemp2, function(err,res){
        if(err) throw err;

        console.log('Last insert ID:', res.insertId);
      });

      con.end(function(err) {
      });
    }
  );
};

当我执行此脚本时,我在控制台上只有“连接已建立”并且没有发生任何事情 - scipt 挂起(我需要 ctrl+c 退出)。 db中也没有新记录。我做错了什么?

【问题讨论】:

    标签: javascript mysql node.js exec


    【解决方案1】:

    您正在声明一个未在脚本中的任何位置调用的start = function () { ... 变量。只需调用它!

    // at end of script
    start();
    

    【讨论】:

      猜你喜欢
      • 2016-05-02
      • 2012-03-10
      • 2020-11-08
      • 1970-01-01
      • 1970-01-01
      • 2017-05-01
      • 2012-02-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多