美文网首页
Nodejs操作数据库

Nodejs操作数据库

作者: 仙姑本姑 | 来源:发表于2021-01-29 15:11 被阅读0次
    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操作数据库

          本文链接:https://www.haomeiwen.com/subject/cbiqtltx.html