node + mysql

Posted 邹喆

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了node + mysql相关的知识,希望对你有一定的参考价值。

1.package.json

{
    "name": "nodezbj",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "author": "",
    "license": "ISC",
    "dependencies": {
        "superagent": "3.5.1",
        "mysql": "2.13.0",
        "cheerio": "0.22.0"
    }
}

2.在 lib 里面新建 sql.js

var mysql = require(‘mysql‘);

function SQL(callback) {
    var connection = mysql.createConnection({
        host: ‘‘,
        user: ‘root‘,
        password: ‘‘,
        database: ‘‘
    });
    connection.connect();
    callback.call(null, connection);
    connection.end();
}


module.exports = {
    query: function(str, callback) {
        SQL(function(connection) {
            connection.query(str, callback);
        });
    }
};

3.node 引用 mysql

var request = require(‘superagent‘);
var cheerio = require(‘cheerio‘)
var sql = require(‘../lib/sql.js‘)


request
    .get(‘http://‘)
    .end(function(err, res) {
        if (err) {
            console.log(err);
            return;
        }

        var $ = cheerio.load(res.text);
        var cateDiv = $(‘.list-category-nav .unstyled.ui-dropdown-menu a‘);

        cateDiv.each(function(index, item) {
            var text = $(item).text();
            var href = $(item).attr(‘href‘);
            console.log(text, href);
            sql.query(‘INSERT INTO cate1 (name, url) VALUES ("‘ + text + ‘", "‘ + href + ‘")‘);
        });

    });

 

以上是关于node + mysql的主要内容,如果未能解决你的问题,请参考以下文章

linux中怎么查看mysql数据库版本

vscode代码片段建议bug

澄清 node.js + promises 片段

node 片段

从mysql的片段中加载ListView

连接MySQL出现错误:ERROR 1045 (28000): Access denied for user ‘root‘@‘localhost‘ (using password: YES)(代码片段