【问题标题】:How to insert json output into mysql with node js如何使用节点 js 将 json 输出插入 mysql
【发布时间】:2017-04-03 11:00:56
【问题描述】:
var express = require('express');
var fs = require('fs');
var mysql = require('mysql');
var request = require('request');
var cheerio = require('cheerio');
var bodyParser = require('body-parser');
var app     = express();

var output;
app.use(bodyParser.json())

app.get('/scrape', function(req, res){
    url = 'https://raitalumni.dypatil.edu/events/?tag=live';

    request(url, function(error, response, html){
        if(!error){
            var $ = cheerio.load(html);
            var json = {
                            title : [],
                            date  : [],
                            month : [],
                            venue : [],
                            link : []
                       };
             output = {
                            events : []
                         };

            $('p.event_name').each(function(){
                json.title.push($(this).text());
            });




            $('p.calendar_date').each(function(){
                json.date.push($(this).text());
            });

            $('span.calendar_month').each(function(){
                json.month.push($(this).text());
            });


            //var fulldate = $('p.calendar_date').concat($('p.calendar_day')).text();
            //console.log('all records: ' + fulldate);

            $('p.event_venue').each(function(){
                json.venue.push($(this).text());
            });

        // var title = $('p.event_name').each(function(){$(this).text()});



            for(var i=0; i<json.title.length; i++){
                output.events[i] = {
                    title : json.title[i],
                    date : json.date[i],
                    month : json.month[i],
                    venue : json.venue[i],
                    link : url
                }
            }

         var connection = mysql.createConnection({
        host: '127.0.0.1',
        port: 3306,
        user: 'root',
        password: '',
        database: 'raithub'
    });


connection.connect(function(error){
   if(!!error){
      console.log('Error');
   }else{
      console.log('Connected to the database!');
   }
});



       var scrape = JSON.stringify(output, null, 4);
       console.log(scrape);

       var query = connection.query("INSERT INTO scrapped ('title','date','month','venue','link') VALUES ('" + output.title + "', '" + output.date + "', '" + output.month + "', '" + output.venue + "', '" + output.link + "');", scrape, function(err, result) {
     if(err) throw err;
     console.log('data inserted');
});


            fs.writeFile('output4.json', JSON.stringify(output, null, 4), function(err){
                console.log('File successfully written! - Check your project directory for the output.json file');
            })

            res.send('Check your console!')         
        }
        else {
            console.log("Network Error, please try again later")
        }
    })
})





app.listen('8000')
console.log('Server running on port 8081');
exports = module.exports = app; 

我哪里出错了?

收到此错误,

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''title','date','month','venue','li
nk') VALUES ('undefined', 'undefined', 'undefi' at line 1 error

【问题讨论】:

    标签: javascript mysql json node.js


    【解决方案1】:

    INSERT 语句应如下所示:

    INSERT INTO table_name (column1, column2, column3, ...)
    VALUES (value1, value2, value3, ...);
    

    列名不应该用引号引起来。您的具体陈述如下:

        var query = connection.query("INSERT INTO scrapped (title,date,month,venue,link) VALUES ('" + output.title + "', '" + output.date + "', '" + output.month + "', '" + output.venue + "', '" + output.link + "');", scrape, function(err, result) {
         if(err) throw err;
         console.log('data inserted');
    });
    

    查看this了解正确的语法

    【讨论】:

    • 这行得通。谢谢。但是当我检查数据库时,我得到所有行的“未定义”值。
    • 知道为什么会这样吗?当输出中有两条记录时,也只更新一行。
    • 那可能是因为 output.title 不是属性。相反 output.event[i].title 可能是因为它看起来像 output 有一个名为 event 的数组属性,并且每个都有 title 等属性。而且您的查询只做一个查询。您需要使用 for 循环来创建更大的查询,并遍历 output.events 数组中的所有元素
    • 正确的语法应该是什么?我想使用标题、日期等插入 mysql 中的不同列?
    • 你能建议如何编码吗?我是 node.js 的新手
    【解决方案2】:

    MySQL 中有一个 JSON 数据类型。

    mysql> CREATE TABLE t1 (jdoc JSON);
    Query OK, 0 rows affected (0.20 sec)
    
    mysql> INSERT INTO t1 VALUES('{"key1": "value1", "key2": "value2"}');
    Query OK, 1 row affected (0.01 sec)
    

    如果您有一个非常大的 json 对象并且不想创建一个巨大的 INSERT 语句,这将特别有用。如果您不确定将通过 json 输入的确切数据但又想捕获所有数据,这也很有用。我目前正在从事一个项目,我们偶尔会在用户输入字段中添加和删除项目,这非常有帮助,因此我不必经常在 MySQL 中更改表和编辑其他语句。

    更多信息可以在这里找到:https://dev.mysql.com/doc/refman/5.7/en/json.html

    【讨论】:

      【解决方案3】:
      const queryString = `insert into table_name(meta) values ('${JSON.stringify(meta)}');`;
      

      【讨论】:

      • 您的答案可以通过添加有关代码的作用以及它如何帮助 OP 的更多信息来改进。
      猜你喜欢
      • 1970-01-01
      • 2017-10-04
      • 2018-03-19
      • 1970-01-01
      • 1970-01-01
      • 2021-05-06
      • 2017-01-22
      • 2020-05-21
      • 1970-01-01
      相关资源
      最近更新 更多