node.js操作mysql实践demo
Posted 码农Doggy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了node.js操作mysql实践demo相关的知识,希望对你有一定的参考价值。
数据表结构
CREATE TABLE `t_records` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增id',
`time` varchar(30) DEFAULT NULL COMMENT '记录时间',
`title` varchar(30) DEFAULT NULL COMMENT '财务标题',
`amount` decimal(10,2) DEFAULT NULL COMMENT '金额',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=83 DEFAULT CHARSET=utf8;
node.js mysql 模块数据库配置(testapiconfig)
var mysql = require('mysql');
var pool = mysql.createPool({
host: '127.0.0.1',
user: 'root',
password: 'root',
database: 'testapi'
});
function query(sql, callblack) {
pool.getConnection(function (err, connection) {
// 使用连接
connection.query(sql, function (err, rows) {
// 使用连接执行查询
if (err) {
//return '[SELECT ERROR] - ' + err
callblack(err);
} else {
callblack(rows);
}
connection.release();
//连接不再使用,返回到连接池
});
});
}
exports.query = query;
node.js 插件 Sequelize ORM数据库配置(SequelizeTestApiconfig)
var Sequelize = require('sequelize');
// database数据库名称 name 用户 password密码
var sequelize = new Sequelize('testapi', 'root', 'root', {
host: 'localhost', //数据库域名
dialect: 'mysql',
port: '3306', //数据库端口
define:{
'charset':'utf-8',
'collate':'utf8_general_ci',
'freezeTableName':true,
'timestamps':true,
},
logging:false,
pool: {
max: 5,
min: 0,
idle: 10000
}
});
module.exports=sequelize;
sequelize数据表模型配置
//引入sequelize模块
var Sequelize = require('sequelize');
//引入Sequelize数据库配置
var db1= require('../db/SequelizeTestApiconfig');
/*
* 定义表的映射模型
* */
module.exports = db1.define('t_records',
{
id: {
type: Sequelize.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
time:{
type: Sequelize.STRING(30),
allowNull: false
},
title:{
type: Sequelize.STRING(30),
allowNull: false
},
amount:{
type: Sequelize.DECIMAL(10,2),
allowNull: false
}
},{
tableName:'t_records',
freezeTableName:true,
timestamps:false,
});
mysql原生sql与Sequelize操作数据库示例
//引入mysql 数据配置
var db = require("../../db/testapiconfig");//原生数据库配置
var Records = require('../../mysqlOrmModel/Records');//关系对象模型映射数据库配置
/**
* 账本记录数据(原生sql)
*/
exports.records_index = function (req, res, next) {
var sql = 'select * from t_records limit ' + "" + req.query.start + "," + req.query.total;
if (req.query.start == undefined || req.query.total == undefined) {
res.json({'status': -1, 'message': '缺失请求参数', 'data': null});
}
db.query(sql, function (rs) {
if (rs.length >= 1) {
res.json({'status': 1, 'message': '数据请求成功', 'data': rs});
} else {
res.json({'status': -1, 'message': '没有数据了!', 'data': rs});
}
});
}
/**
* 查找账本记录数据(ORM 操作mysql)
*/
exports.index = function (req, res, next) {
if(req.query.id==undefined){
res.json({'status': -1, 'message': '缺失请求参数', 'data': null});
}else{
Records.findOne({where: {id: req.query.id}}).then(records => {
res.json(records);
});
}
}
/**
* 添加账本记录(原生sql)
* */
exports.add_record = function (req, res, next) {
if (req.query.time == undefined || req.query.title == undefined || req.query.amount == undefined) {
res.json({'status': -1, 'message': '缺失请求参数', 'data': req.query});
} else {
let sql = "INSERT INTO `t_records` (`time`,`title`,`amount`) VALUES (" + req.query.time + "," + req.query.title + "," + req.query.amount + ")";
db.query(sql, function (rs) {
if (rs.changedRows != undefined) {
res.json({'status': 1, 'message': '添加成功', 'data': rs, 'sql': sql});
} else {
res.json({'status': -1, 'message': '添加数据失败', 'data': rs, 'sql': sql});
}
});
}
}
/**
* 删除账本记录(原生sql)
* @param req
* @param res
* @param next
*/
exports.del_record = function (req, res, next) {
if (req.query.id == undefined) {
res.json({'status': -1, 'message': '缺失请求参数', 'data': null});
} else {
let sql = "DELETE FROM `t_records` WHERE ( id=" + req.query.id + ")";
db.query(sql, function (rs) {
if (rs.changedRows != undefined) {
res.json({'status': 1, 'message': '删除成功', 'data': rs, 'sql': sql});
} else {
res.json({'status': -1, 'message': '删除数据失败', 'data': rs, 'sql': sql});
}
});
}
}
/**
*统计账本记录总条数(原生sql)
*/
exports.total = function (req, res, next) {
let sql = "SELECT COUNT(*) AS tp_count FROM `t_records` LIMIT 1 "
db.query(sql, function (rs) {
if (rs.changedRows != undefined) {
res.json({'status': 1, 'message': '统计成功', 'data': rs, 'sql': sql});
} else {
res.json({'status': -1, 'message': '统计失败', 'data': rs, 'sql': sql});
}
});
}
/**
*更新账本记录数据(原生sql)
*/
exports.up_record = function (req, res, next) {
let sql = get_up_record_sql(req);
if (sql == "" || req.query.id == undefined) {
res.json({'status': -1, 'message': '缺失更新条件', 'data': null});
} else {
let upsql = "UPDATE t_records SET " + sql + " WHERE id=" + req.query.id;
db.query(upsql, function (rs) {
if (rs.changedRows != undefined) {
res.json({'status': 1, 'message': '数据更新成功', 'data': rs, 'sql': upsql});
} else {
res.json({'status': -1, 'message': '数据更新失败', 'data': rs, 'sql': upsql});
}
});
}
}
/**
* @param req 获取请求参数生成查询更新账本记录(原生sql)
* @returns {string}
*/
function get_up_record_sql(req) {
var sql = "";
var sqlfield = new Array();
if (req.query.time != undefined) {
sqlfield.push(['time', req.query.time]);
}
if (req.query.title != undefined) {
sqlfield.push(['title', req.query.title]);
}
if (req.query.amount != undefined) {
sqlfield.push(['amount', req.query.amount]);
}
if (sqlfield.length > 1) {
for (let i = 0; i < sqlfield.length; i++) {
if (i == sqlfield.length - 1) {
//最后一个元素不加逗号 ","
sql += sqlfield[i][0] + "=" + sqlfield[i][1];
} else {
sql += sqlfield[i][0] + "=" + sqlfield[i][1] + ",";
}
}
} else {
sql += sqlfield[0][0] + "=" + sqlfield[0][1];
}
return sql;
}
以上是关于node.js操作mysql实践demo的主要内容,如果未能解决你的问题,请参考以下文章
node.js零基础详细教程:node.js操作mongodb,及操作方法的封装