了解了一下 nodejs ,发现它还能连接mysql、mongoDB,连接方式还比较简便,没啥jdbc的七大步;测通看一下;
代码稀烂,不过能跑通看下结果
首先数据库整点测试数据
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 50540
Source Host : localhost:3306
Source Database : csl
Target Server Type : MYSQL
Target Server Version : 50540
File Encoding : 65001
Date: 2021-07-01 16:32:57
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for students
-- ----------------------------
DROP TABLE IF EXISTS `students`;
CREATE TABLE `students` (
`id` int(3) NOT NULL AUTO_INCREMENT COMMENT '主键',
`name` varchar(10) NOT NULL COMMENT '姓名',
`age` int(3) NOT NULL COMMENT '年龄',
`class_name` varchar(10) NOT NULL COMMENT '班级',
`sex` int(11) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of students
-- ----------------------------
INSERT INTO `students` VALUES ('1', '詹溪', '18', '高三(2)班', '0');
INSERT INTO `students` VALUES ('2', '徐柯', '18', '高三(3)班', '0');
INSERT INTO `students` VALUES ('3', '蓝毅', '17', '高三(3)班', '0');
INSERT INTO `students` VALUES ('4', '温邱', '18', '高三(3)班', '0');
INSERT INTO `students` VALUES ('5', '王五', '18', '大一', '1');
INSERT INTO `students` VALUES ('6', '王五', '25', '大一', '1');
INSERT INTO `students` VALUES ('7', '赵六', '95', '社会大学', '1');
INSERT INTO `students` VALUES ('8', '小明', '14', '初二', '1');
INSERT INTO `students` VALUES ('9', '刘备', '62', '大一', '1');
INSERT INTO `students` VALUES ('10', '孙尚香', '20', '大三', '0');
INSERT INTO `students` VALUES ('11', '貂蝉', '62', '大一', '0');
INSERT INTO `students` VALUES ('12', '妲己', '8', '四年级', '0');
INSERT INTO `students` VALUES ('13', '赵云', '33', '社会大学', '1');
INSERT INTO `students` VALUES ('14', '王昭君', '66', '社会大学', '0');
INSERT INTO `students` VALUES ('15', '诸葛亮', '12', '初二', '1');
INSERT INTO `students` VALUES ('16', 'AK47', '45', '社会大学', '1');
INSERT INTO `students` VALUES ('17', '雷神', '31', '社会大学', '0');
INSERT INTO `students` VALUES ('18', '火麒麟', '40', '社会大学', '1');
写代码
按照java mvc(其实结构不准确,很混乱待优化)的结构弄下吧,dao层操作数据库,好像node服务也可以弄数据库连接池,还没弄,弄个简单的连接测试下
dao.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123456',
database: 'csl'
});
connection.connect();
var daoObj = function () {
this.select = function (params) {
console.log('DAO:', params)
return new Promise((resolve, reject) => {
//设计了几个参数制作sql语句
let {
tableName,
pageNo,
pageSize,
orderBy
} = params
var sql = `SELECT * FROM ${tableName ? tableName : 'students'} ${orderBy ? `order by id ${orderBy}`:''} ${pageNo && pageSize ? `limit ${(pageNo-1)*pageSize},${pageSize}` : ''}`;
console.log('sql', sql)
connection.query(sql, function (err, result) {
if (err) {
console.log('[SELECT ERROR] - ', err.message);
reject('[SELECT ERROR] - ' + err.message);
} else {
console.log('--------------------------SELECT----------------------------');
resolve(result)
console.log('------------------------------------------------------------\n\n');
}
});
// connection.release()
// connection.end();
})
}
this.add = async function (params) {
return '暂未开发'
}
this.del = async function (params) {
return '暂未开发'
}
this.upd = async function (params) {
return '暂未开发'
}
}
module.exports = daoObj;
弄完操作数据库的再来弄http服务
server.js
var http = require("http");
var url = require("url");
//增加换行打印的好看点
function getResultStr(result) {
let str = ''
result.forEach((item, index) => {
str += `\n${index}: ${JSON.stringify(item)}`
});
return str
}
function start(route) {
async function onRequest(request, response) {
request.setEncoding('utf-8')
var pathname = url.parse(request.url).pathname;
var query = decodeURIComponent(url.parse(request.url).query);
response.writeHead(200, {
'Content-Type': 'application/json;charset=utf-8'
});
let content = `\n内容:城南花已开~ 40已不在 \n路由:${pathname}\n参数:${query}\n\n--------------------------------------- 分割线 ---------------------------------------\n\n`
let result = await route(pathname, query);//这个就是查数据的外包装方法
result = JSON.parse(JSON.stringify(result))
content += `操作:${result.optionName}` + getResultStr(result.result)
response.write(content);
response.end();
}
http.createServer(onRequest).listen(8040);
console.log("Server has started.");
}
exports.start = start;
中间层
router.js
var daoObj = require('./dao')
var daoObj = new daoObj()
async function route(pathname, query) {
if (pathname == '/favicon.ico') {
return
}
console.log("请求路径: " + pathname + " ----router");
console.log("请求参数为:", query + " ----router")
let option = {}
//将url中的参数转成对象的形式
function urlParamsToObj(str) {
arr = str.split('&')
let objResult = {}
for (let i = 0; i < arr.length; i++) {
let key = arr[i].split('=')[0]
let value = arr[i].split('=')[1]
objResult[key] = value
}
return objResult
}
option.params = urlParamsToObj(query)
if(!option.params.tableName){
option.params.tableName = 'students'
}
switch (pathname) {
case '/query':
option.optionName = '查询所有'
option.result = await daoObj.select(option.params)
break;
case '/add':
option.optionName = '增加字段'
option.result = await daoObj.add(option.params)
break;
case '/delete':
option.optionName = '删除字段'
option.result = await daoObj.del(option.params)
break;
case '/update':
option.optionName = '更新字段'
option.result = await daoObj.upd(option.params)
break;
default:
option.optionName = 'other'
break;
}
return option
}
exports.route = route;
服务运行入口
index.js
var server = require("./server");
var router = require("./router");
server.start(router.route);
启动
node index.js
发请求测试
阿巴阿巴阿巴,以后简单的东西后端大佬没空做,咱就不要大佬了,自己做,自己(nodejs)给自己(js)服务,有趣;