nodejs下mysql编程入门实例

首页我们需要先安装mysql模块,执行如下命令

npm install mysql -save

以上为使用命令安装mysql并添加依赖

以下实例为查询mysql中的spider数据库中的page_info表,并打印信息,这里文件存放路径为:D:\nodejs\routes\system\baseDB.js

var mysql = require('mysql');

var DATABASE = 'spider';

//创建连接  
var client = mysql.createConnection({
    host: '127.0.0.1',
    user: 'root',
    password: 'root',
    database: 'spider'
});

client.connect();

client.query(
    'SELECT * FROM page_info',
    function selectCb(err, results, fields) {
        if (err) {
            throw err;
        }
      
        if(results) {
            for(var i = 0; i < results.length; i++) {
                console.log("%d\t%s\t%s", results[i].page_id, results[i].title, results[i].spider_url);
            }
        }
        client.end();
    }
);


执行如下命令查看结果

node routes/system/baseDB.js
结果如下图


以下为mysql链接信息从配置文件引

config.js

exports.mysql = {
    host: '127.0.0.1',
    user: 'root',
    password: 'root',
    database: 'spider'
};
db.js

var mysql = require('mysql');
var config = require('../config');

//创建连接  
var client = mysql.createConnection({
    host: config.mysql.host,
    user: config.mysql.user,
    password: config.mysql.password,
    database: config.mysql.database
});

client.connect();

client.query(
    'select * from page_info',
    function selectCb(err, results, fields) {
        if (err) {
            throw err;
        }
      
        if(results) {
            for(var i = 0; i < results.length; i++) {
                console.log("%d\t%s\t%s", results[i].page_id, results[i].title, results[i].spider_url);
            }
        }
        client.end();
    }
);

感谢您的阅读,希望对您有帮助,本文版权归 #惊讶# 所有

评论 (0)