关于NodeJs访问MySQL

关于NodeJs访问MySQL

1、安装mysql模块。
在cmd命令中输入:npm install mysql

2、编写一个test.js文件。

var mysql = require('mysql');

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

connection.connect();

// 查询
var sql = 'select * from app_users';
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');  
    if(result) {
        for (var i = 0; i < result.length; i++) {
            console.log("%d\t%s\t%s", result[i].user_id, result[i].user_code, result[i].user_name);
        }
    }
    console.log('---------------------------------\n\n');  
});

// 增加
var addSql = 'insert into app_users(user_code, user_name) values(?, ?)';
var addSqlParams = ['9004', 'jiangzhihao'];

connection.query(addSql, addSqlParams, function (err, result) {
    if(err) {
        console.log('[INSERT ERROR] - ',err.message);
        return;
    }
    console.log('insert---------------------------------');     
    console.log('insert:', result);        
    console.log('---------------------------------\n\n');  
});

// 修改
var modSql = 'update app_users set user_name = ?, user_code = ? where user_id = ?';
var modSqlParams = ['jiang001', '9005', 4];

connection.query(modSql, modSqlParams, function (err, result) {
    if(err) {
        console.log('[UPDATE ERROR] - ', err.message);
        return;
    }
    console.log('update---------------------------------');
    console.log('update affectedRows', result.affectedRows);
    console.log('---------------------------------\n\n');
});

// 删除
var delSql = 'delete from app_users where user_id=5';

connection.query(delSql,function (err, result) {
    if(err) {
        console.log('[DELETE ERROR] - ',err.message);
        return;
    }
    console.log('delete---------------------------------');
    console.log('delete affectedRows',result.affectedRows);
    console.log('---------------------------------\n\n');
});

connection.end();

3、测试结果

发表回复

您的电子邮箱地址不会被公开。