发表日期: 2021-05-07 10:15:48 浏览次数:57
尉氏申请400电话费用【尉氏企业全国热线电话办理】尉氏开通400电话电信价格、尉氏微信公众号代运营外包托管、尉氏网店编辑装修美工、尉氏网站推广优化大概需要多少钱
尉氏县位于豫东平原,属河南省开封市。东邻通许县、扶沟县,南与鄢陵县、长葛县接壤,西与新郑市交界,北与祥符区、中牟县相连。南北长40.77公里,东西宽43.76公里,总面积约1307.7平方公里,总人口81万人(2000年),中共尉氏县委、尉氏县人民政府驻地:两湖街道。 [1]
尉氏古称“尉州”,是河南省经济管理扩权县,电价趸售优惠县,拥有省政府批准的全省八大特色基地之一的河南省中原纺织工业基地,省认定的尉氏高效农业示范园区。 [2]
2018年,全县完成地区生产总值388亿元,增长8%;一般公共预算收入首次突破20亿元、达到20.6亿元,增长16.8%;税收收入15.96亿元,增长29.9%;城镇和农村居民人均可支配收入预计达到26951元、13911元,分别增长8.3%和8.9%。 [3]
ndoe中实现数据的持久化的多种方法
文件系统 fs
数据库
1 关系型数据库 mysql
2 文档型数据库 mongodb
3 键值的对数据库 redis
文件系统数库
//fsdb.js
//实现一个文件系统读取数据库
const fs = require("fs")
function get(key){
fs.readFile("./db.json", (err, data)=>{
const json = JSON.parse(data)
console.log(json[key])
})
}
fonction set(key, value){
//可能是空文件, 则设置为空对象
const json = data ? JSOJN.parse(data):[]
json[key] = value//设置值
fs.writeFile('./db.json', JSON.stringify(json), err=>{
if(err){console.log(err)}
console.log('写入成功')
})
}
//命令行接口部分
const readline = require('readline')
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
rl.on('line', function(input){
const [op, key, value] = require.split(' ')
if(op === 'get){
get(key)
}else if(op === 'set){
set(key, value)
}else if(op === 'quit'){
rl.close()
}else{
console.log('没有该操作')
}
})
rl.on('close', function(){
console.log(''程序结束)
process.exit(0)
})
node.js原生驱动
安装mysql模块 npm i mysql --save
mysql模块的基本使用
//mysql.js
const mysql = require('mysql')
//链接配置
const cfg = {
host: 'localhost',
user: 'root',
password: ' example',
database: 'kkk',//确保数据库存在
}
//创建连接对象
const conn = mysql.createConnection(cfg)
//链接
conn.connect(err=>{
if(err){
throw err
}else{
console.log('connect success')
}
})
//查询 conn.query()
//创建表
const CREATE_SQL = `
CREATE TABLE IF NOT EXISTS TEST(
id INT NULL AUTO_INCREMENT,
message VARCHAR(45) NULL,
PRIMARY KEY (id)
)`
const INSERT_SQL = `INSERT INTO test(message) VALUES(?)`
const SELECT_SQL = `SELECT * FROM test`
conn.query(CREATE_SQL, err=>{
if(err){throw err}
//
conn.query(INSERT_SQL, 'hellow,world', (err, result)=>{
if(err){throw err}
console.log(result)
conn.query(SELECT_SQL, (err, result)=>{
console.log(result)
conn.end()//若query语句有嵌套,则end需要在此执行
})
})
})
`
es2017 写法
// mysql2.js
(async () => {
// get the client
const mysql = require('mysql2/promise');
// 连接配置
const cfg = {
host: "localhost",
user: "root",
password: "example", // 修改为你的密码
database: "kaikeba" // 请确保数据库存在
};
// create the connection
const connection = await mysql.createConnection(cfg);
// 查询 conn.query()
// 创建表
const CREATE_SQL = `CREATE TABLE IF NOT EXISTS test (
id INT NOT NULL AUTO_INCREMENT,
message VARCHAR(45) NULL,
PRIMARY KEY (id))`;
const INSERT_SQL = `INSERT INTO test(message) VALUES(?)`;
const SELECT_SQL = `SELECT * FROM test`;
// query database
let ret = await connection.execute(CREATE_SQL);
console.log('create:', ret)
ret = await connection.execute(INSERT_SQL, ['abc']);
console.log('insert:', ret)
const [rows, fields] = await connection.execute(SELECT_SQL);
console.log('select:', rows)
})()
node.js ORM – Sequelize
概述 基于Promise的ORM,支持多种数据库,事物,关联等
安装 npm i sequelize mysql2 -S
基本使用
(async () => {
const Sequelize = require("sequelize");
// 建⽴连接
const sequelize = new Sequelize("kaikeba", "root", "example", {
host: "localhost",
dialect: "mysql",
operatorsAliases: false
});
// 定义模型
const Fruit = sequelize.define("Fruit", {
name: { type: Sequelize.STRING(20), allowNull: false },
price: { type: Sequelize.FLOAT, allowNull: false },
stock: { type: Sequelize.INTEGER, defaultValue: 0 }
});
let ret = await Fruit.sync()
console.log('sync',ret)
ret = await Fruit.create({
name: "⾹蕉",
price: 3.5
})
console.log('create',ret)
ret = await Fruit.findAll()
await Fruit.update(
{ price: 4 },
{ where: { name:'⾹蕉'} }
)
console.log('findAll',JSON.stringify(ret))
const Op = Sequelize.Op;
ret = await Fruit.findAll({
// where: { price: { [Op.lt]:4 }, stock: { [Op.gte]: 100 } }
where: { price: { [Op.lt]: 4, [Op.gt]: 2 } }
})
console.log('findAll', JSON.stringify(ret, '', '\t'))
})()
强制同步:创建表之前先删除已存在的表
Fruit.sync({ force: true })
避免自动生成时间戳字段
const Fruit = sequelize.define("Fruit", {}, {
timestamps: false
});
指定表名freezeTableName: true 或 tableName:'xxx'
设置前者则以modelName作为表名;设置后者则按其值作为表名。
蛇形命名 underscored: true,
默认驼峰命名
UUID 主键
id: {
type: Sequelize.DataTypes.UUID,
defaultValue: Sequelize.DataTypes.UUIDV1,
primaryKey: true
},
Getters & Setters:可⽤于定义伪属性或映射到数据库字段的保护属性
// 定义为属性的⼀部分
name: {
type: Sequelize.STRING,
allowNull: false,
get() {
const fname = this.getDataValue("name");
const price = this.getDataValue("price");
const stock = this.getDataValue("stock");
return `${fname}(价格:¥${price} 库存:${stock}kg)`;
}
}
// 定义为模型选项
// options中 {
getterMethods:{
amount(){
return this.getDataValue("stock") + "kg";
}
},
setterMethods:{
amount(val){
const idx = val.indexOf('kg');
const v = val.slice(0, idx);
this.setDataValue('stock', v);
}
}
}
// 通过模型实例触发setterMethods
Fruit.findAll().then(fruits => {
console.log(JSON.stringify(fruits));
// 修改amount,触发setterMethods
fruits[0].amount = '150kg';
fruits[0].save();
});
校验:可以通过校验功能验证模型字段格式、内容,校验会在 create 、 update 和 save 时⾃动运行
price: {
validate: {
isFloat: { msg: "价格字段请输⼊数字" },
min: { args: [0], msg: "价格字段必须⼤于0" }
}
},
stock: {
validate: {
isNumeric: { msg: "库存字段请输⼊数字" }
}
}
模型扩展:可添加模型实例⽅法或类⽅法扩展模型
// 添加类级别⽅法
Fruit.classify = function(name) {
const tropicFruits = ['⾹蕉', '芒果', '椰⼦']; // 热带⽔果
return tropicFruits.includes(name) ? '热带⽔果':'其他⽔果';
};
// 添加实例级别⽅法
Fruit.prototype.totalPrice = function(count) {
return (this.price * count).toFixed(2);
};
// 使⽤类⽅法
['⾹蕉','草莓'].forEach(f => console.log(f+'是'+Fruit.classify(f)));
// 使⽤实例⽅法
Fruit.findAll().then(fruits => {
const [f1] = fruits;
console.log(`买5kg${f1.name}需要¥${f1.totalPrice(5)}`);
});
数据查询
// 通过id查询(不⽀持了)
Fruit.findById(1).then(fruit => {
// fruit是⼀个Fruit实例,若没有则为null
console.log(fruit.get());
});
// 通过属性查询
Fruit.findOne({ where: { name: "⾹蕉" } }).then(fruit => {
// fruit是⾸个匹配项,若没有则为null
console.log(fruit.get());
});
// 指定查询字段
Fruit.findOne({ attributes: ['name'] }).then(fruit => {
// fruit是⾸个匹配项,若没有则为null
console.log(fruit.get());
});
// 获取数据和总条数
Fruit.findAndCountAll().then(result => {
console.log(result.count);
console.log(result.rows.length);
});
// 查询操作符
const Op = Sequelize.Op;
Fruit.findAll({
// where: { price: { [Op.lt]:4 }, stock: { [Op.gte]: 100 } }
where: { price: { [Op.lt]:4,[Op.gt]:2 }}
}).then(fruits => {
console.log(fruits.length);
});
// 或语句
Fruit.findAll({
// where: { [Op.or]:[{price: { [Op.lt]:4 }}, {stock: { [Op.gte]: 100
}}] }
where: { price: { [Op.or]:[{[Op.gt]:3 }, {[Op.lt]:2 }]}}
}).then(fruits => {
console.log(fruits[0].get());
});
// 分⻚
Fruit.findAll({
offset: 0,
limit: 2,
})
// 排序
Fruit.findAll({
order: [['price', 'DESC']],
})
// 聚合
Fruit.max("price").then(max => {
console.log("max", max);
});
Fruit.sum("price").then(sum => {
console.log("sum", sum);
});
更新
Fruit.findById(1).then(fruit => {
// ⽅式1
fruit.price = 4;
fruit.save().then(()=>console.log('update!!!!'));
});
// ⽅式2
Fruit.update({price:4}, {where:{id:1}}).then(r => {
console.log(r);
console.log('update!!!!')
})
删除
// ⽅式1
Fruit.findOne({ where: { id: 1 } }).then(r => r.destroy());
// ⽅式2
Fruit.destroy({ where: { id: 1 } }).then(r => console.log(r));
const log = (text, data) => {
console.log(`===========${text}========`)
console.log(JSON.stringify(data,null,"\t"))
console.log(`==========================`)
}
const sequelize = require('./util/database')
// 定义模型 1:N 关系
const Product = require('./models/product');
const User = require('./models/user');
const Cart = require('./models/cart');
const CartItem = require('./models/cart-item');
Product.belongsTo(User, {
constraints: true,
onDelete: 'CASCADE'
});
User.hasMany(Product)
await sequelize.sync({ force: true })
// 创建⽤户
let user = await User.fin
if (!user) {
user = await User.create({
name: 'kaikeba',
email: 'mail@kaikeba.com'
})
}
// 添加商品
let product = await user.createProduct({
title: '商品⼀',
price: 123,
imageUrl: 'abc.png',
description: '商品描述'
})
log('product', product)
// N : N关系
User.hasOne(Cart)
Cart.belongsTo(User)
Cart.belongsToMany(Product, {
through: CartItem
});
Product.belongsToMany(Cart, {
through: CartItem
});
await sequelize.sync({ force: true })
// 创建⽤户
let user = await User.findByPk(1)
if (!user) {
user = await User.create({
name: 'kaikeba',
email: 'mail@kaikeba.com'
})
}
// 添加商品
let product = await user.createProduct({
title: '商品⼀',
price: 123,
imageUrl: 'abc.png',
description: '商品描述'
})
log('product', product)
// 添加购物⻋
await user.createCart()
ret = await User.findAll({ include: [Cart] })
log('getCart:', ret)
// 添加购物⻋商品
let cart = await user.getCart()
await cart.addProduct(product, {
through: {
quantity: 1 }
})
// 获取购物⻋商品数量
const productId = 1
const item = await cart.getProducts({
where: {
id: productId
}
})
log('item', item)
// 商品是否存在
if(item.length > 0){
console.log('商品存在....................')
await cart.addProduct(product, {
through: {
quantity: item[0].cartItem.quantity + 1 }
})
}else{
await cart.addProduct(product, {
through: {
quantity: 1 }
})
}
log('cart', cart)
尉氏申请400电话费用【尉氏企业全国热线电话办理】尉氏开通400电话电信价格、尉氏微信公众号代运营外包托管、尉氏网店编辑装修美工、尉氏网站推广优化大概需要多少钱
备案号: 苏ICP备11067224号
CopyRight © 2011 书生商友信息科技 All Right Reserved
24小时服务热线:400-111-6878 E-MAIL:1120768800@qq.com QQ:1120768800
网址: https://www.768800.com 网站建设:上往建站
关键词: 网站建设| 域名邮箱| 服务器空间| 网站推广| 上往建站| 网站制作| 网站设计| 域名注册| 网络营销| 网站维护|
企业邮箱| 虚拟主机| 网络建站| 网站服务| 网页设计| 网店美工设计| 网站定制| 企业建站| 网站设计制作| 网页制作公司|
400电话办理| 书生商友软件| 葬花网| 调温纤维| 海洋馆运营维护| 北京保安公司| 殡仪馆服务| 殡葬服务| 昌平殡葬| 朝阳殡葬|
欢迎您免费咨询,请填写以下信息,我们收到后会尽快与您联系
服务热线:400-111-6878