Nodejs操作数据库

var mysql = require('mysql');

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

connection.connect();

var sql = 'SELECT * FROM pieziyuan';
var id = [];
var name = [];
var resultJSON = [];
connection.query(sql, function(err, result) {
    if (err) {
        console.log('[SELECT ERROR] - ', err.message);
        return;
    }
    console.log('--------------------------SELECT----------------------------');
    console.log(result);
    console.log('------------------------------------------------------------\n\n');


    for (var i = 0; i < result.length; i++) {
        resultJSON[i] = result[i];
        id[i] = result[i].id;
    }

    a = JSON.stringify(resultJSON);

    console.log(a);

    var fs = require('fs');
    fs.writeFile('user.json', a, function(error) { //json文件写入到data文件夹下
        if (error) console.log('json-文件写入失败');
    });
});



connection.end();

你可能感兴趣的:(Nodejs操作数据库)