当前位置: 首页 > news >正文

网站代码开发文档模板网络营销的优化和推广方式

网站代码开发文档模板,网络营销的优化和推广方式,网站建设和网站运营包括什么,网上学电脑培训中心前言 前面我们已经介绍了第二阶段的第1-4点内容,本篇介绍第5点内容:数据库集成(koamysql) 也是第二阶段内容的完结。 一、学习目标 在koa项目中正常连接数据库,对数据表进行增删改查的操作。 二、操作步骤 本篇文章…

前言

前面我们已经介绍了第二阶段的第1-4点内容,本篇介绍第5点内容:数据库集成(koa+mysql)

也是第二阶段内容的完结。

一、学习目标

在koa项目中正常连接数据库,对数据表进行增删改查的操作。

二、操作步骤

本篇文章会使用到:koa+sequelize+mysql+apipost(用于测试http方法)

注意:文章很多的操作步骤和“express框架的数据库集成”基本上是一样的,参考文章:

【express-generator】09-连接和使用数据库-CRUD 操作(第二阶段完结)-CSDN博客

所以文章中会简单跳过/省略一些简单的步骤。

1、安排依赖

在项目根目录下运行以下命令安装必要的依赖:

npm install koa mysql2 sequelize koa-router koa-bodyparser

 2、配置数据库连接

注意:每个人的数据库连接连接信息不一样,对应修改自己的信息。

state2/models/dbConnect.js中配置数据库连接信息:

// 该文件负责连接数据库
const { Sequelize } = require("sequelize");// 创建数据库连接
const sequelize = new Sequelize("mysite2", "root", "123456aa", {host: "localhost",dialect: 'mysql',logging: false
});const startDB=async()=> {try {await sequelize.authenticate();console.log('数据库已建立起连接.');} catch (error) {console.error('Unable to connect to the database:', error);}
}
startDB()// 向外暴露这个连接实例
module.exports = sequelize;

3、定义数据模型

在state2/models/userModel写入以下代码:

const { DataTypes } = require("sequelize");
const sequelize = require("./dbConnect");// 定义数据模型
module.exports = sequelize.define("koauser", {// 这张表拥有哪些字段name : {type : DataTypes.STRING,allowNull : true},age : {type : DataTypes.INTEGER,allowNull : true},
},{//与模型定义时的名称一致。 // 比如定义了上述定义了content模型,设置了这个字段,创建表的名字也是content。freezeTableName : true,  //用于记录数据的创建时间和更新时间。createdAt : false,  updatedAt : false
});

这里我们定义了一个名为“koauser”的数据表,有name和age字段,分别是string和integer数据类型。 

4、初始化Sequelize和加载模型

在state2/demodels/db.js写入以下代码:

// 该文件负责对数据库进行一个初始化操作
const sequelize = require("./dbConnect"); // 数据库连接实例const userModel = require("./userModel"); // 数据模型
const initData=async function () {// 将数据模型和表进行同步await sequelize.sync({alter: true,})// 同步完成之后,有一些表是需要一些初始化数据// 查询这张表有没有内容,没有内容才初始化数据const userCount = await userModel.count();if (!userCount) {// 进入此 if,说明该表没有数据,我们进行一个初始化await userModel.create({name: "Tom",age:18})console.log("初始化内容数据表数据完毕...");}console.log("数据库数据已经准备完毕....");
}
initData()

5、创建Koa应用并集成Sequelize

在state2/demo5.js中写入以下代码:

const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
// const models = require('./models');
const userModel = require('./models/userModel');
const app = new Koa();
const router = new Router();require('./models/db');
// 使用bodyParser中间件解析请求体
app.use(bodyParser());// 定义路由
router.get('/', async (ctx) => {ctx.body = 'Welcome to Koa with Sequelize!';
});// 使用路由中间件
app.use(router.routes()).use(router.allowedMethods());app.listen(3000, () => {console.log('Server is running at http://localhost:3000');
});

启动服务,看是否正常连接数据库和创建、初始化数据表。 

在state2的目录下打开终端,执行node demo5.js

启动之前,数据库的表情况 

启动之后,多了一个koauser的数据表,并且有一条数据。

6、增删改查(CRUD)操作

Create:增加

Read:查

Update:更新

Delete:删除

6.1、查找所有用户信息

在state2/demo5.js中新增代码:

// 查找所有用户
router.get('/users', async (ctx) => {const users = await userModel.findAll();ctx.body = users;
});

方法放在这个位置

测试:启动服务+apipost工具

新增get方法,点击发送则会得到以下结果

6.2、 增加新的用户

//   创建用户
router.post('/user', async (ctx) => {const { name, age } = ctx.request.body;try {const user = await userModel.create({ name,age });ctx.body = user;} catch (error) {ctx.status = 400;ctx.body = { error: error.message };}
});

测试:启动服务+添加post方法

 在数据表中刷新可以看到新增的数据项

6.3、查找单条用户数据

为了后续测试,先增加了几条数据

 

// 查找单个用户
router.get('/user/:id', async (ctx) => {const { id } = ctx.params;try {const user = await userModel.findByPk(id);if (user) {ctx.body = user;} else {ctx.status = 404;ctx.body = { error: 'User not found' };}} catch (error) {ctx.status = 400;ctx.body = { error: error.message };}
});

测试:启动服务+添加get方法

查找id为1的数据项

查找id为3的数据项

 6.4、更新用户信息

  // 更新用户router.put('/user/:id', async (ctx) => {const { id } = ctx.params;const { name,age } = ctx.request.body;try {const user = await userModel.findByPk(id);if (user) {await user.update({ name,age });ctx.body = user;} else {ctx.status = 404;ctx.body = { error: 'User not found' };}} catch (error) {ctx.status = 400;ctx.body = { error: error.message };}});

 测试:启动服务+测试put方法

我们尝试将id为1的数据项,对name进行修改成"Rura"(原本是Tom)

响应结果

 刷新数据表,可以看见id为1的数据项的name已经被修改。

6.5、删除用户信息

  // 删除用户router.delete('/user/:id', async (ctx) => {const { id } = ctx.params;try {const user = await userModel.findByPk(id);if (user) {await user.destroy();ctx.status = 204;} else {ctx.status = 404;ctx.body = { error: 'User not found' };}} catch (error) {ctx.status = 500;ctx.body = { error: error.message };}});

测试:启动服务+测试delete方法

这里我们尝试将id为4的数据项进行删除

点击发送,在数据表中刷新查看结果。

三、小结

这篇我们介绍了在koa中如何使用数据库,创建和初始化数据表,并介绍了数据表的常用操作:增删改查,文章以“代码示范+测试”的内容呈现。文章中用到的代码示范,我已经同步更新在代码仓库中,有需要的朋友请自行获取:koa练习: koa练习

欢迎大家star和fork,也欢迎一起完善这个代码仓~

koa专栏的第二阶段的内容到此结束,后续的文章我会更新第三阶段的内容。

关注我,及时获取最新文章消息~


文章转载自:
http://shandite.xxhc.cn
http://sprinkler.xxhc.cn
http://nestle.xxhc.cn
http://mesmerize.xxhc.cn
http://statesmanlike.xxhc.cn
http://fishy.xxhc.cn
http://nebulium.xxhc.cn
http://viticolous.xxhc.cn
http://stableboy.xxhc.cn
http://solvolysis.xxhc.cn
http://shittah.xxhc.cn
http://albert.xxhc.cn
http://kop.xxhc.cn
http://pants.xxhc.cn
http://michael.xxhc.cn
http://mineralocorticoid.xxhc.cn
http://popover.xxhc.cn
http://rojak.xxhc.cn
http://concessively.xxhc.cn
http://samarskite.xxhc.cn
http://ndis.xxhc.cn
http://mathematization.xxhc.cn
http://homeothermic.xxhc.cn
http://ormolu.xxhc.cn
http://cuppy.xxhc.cn
http://picometre.xxhc.cn
http://loanword.xxhc.cn
http://chick.xxhc.cn
http://prosthodontia.xxhc.cn
http://gelsenkirchen.xxhc.cn
http://herpangina.xxhc.cn
http://betweentimes.xxhc.cn
http://excise.xxhc.cn
http://elysium.xxhc.cn
http://wedeling.xxhc.cn
http://colorway.xxhc.cn
http://coyness.xxhc.cn
http://hanjiang.xxhc.cn
http://litotes.xxhc.cn
http://concessive.xxhc.cn
http://cosmonautics.xxhc.cn
http://indigenize.xxhc.cn
http://pillaret.xxhc.cn
http://saxicavous.xxhc.cn
http://metralgia.xxhc.cn
http://were.xxhc.cn
http://minisize.xxhc.cn
http://biradial.xxhc.cn
http://mistle.xxhc.cn
http://floccus.xxhc.cn
http://ramrod.xxhc.cn
http://doat.xxhc.cn
http://nonplus.xxhc.cn
http://sunnism.xxhc.cn
http://lancewood.xxhc.cn
http://decreasingly.xxhc.cn
http://atheromatosis.xxhc.cn
http://multifamily.xxhc.cn
http://inimically.xxhc.cn
http://sporozoite.xxhc.cn
http://divinylbenzene.xxhc.cn
http://fireworm.xxhc.cn
http://exopathic.xxhc.cn
http://garnet.xxhc.cn
http://degeneracy.xxhc.cn
http://nagging.xxhc.cn
http://apophysis.xxhc.cn
http://rooflet.xxhc.cn
http://cheapshit.xxhc.cn
http://colone.xxhc.cn
http://parent.xxhc.cn
http://essene.xxhc.cn
http://sensum.xxhc.cn
http://tannia.xxhc.cn
http://hunk.xxhc.cn
http://diener.xxhc.cn
http://cow.xxhc.cn
http://cabana.xxhc.cn
http://hmf.xxhc.cn
http://olivaceous.xxhc.cn
http://harbin.xxhc.cn
http://voluminal.xxhc.cn
http://hungover.xxhc.cn
http://ecology.xxhc.cn
http://brs.xxhc.cn
http://striate.xxhc.cn
http://catstep.xxhc.cn
http://ckd.xxhc.cn
http://consensual.xxhc.cn
http://clampdown.xxhc.cn
http://geopolitic.xxhc.cn
http://scissor.xxhc.cn
http://intensification.xxhc.cn
http://emancipatory.xxhc.cn
http://polluted.xxhc.cn
http://apiece.xxhc.cn
http://toxigenesis.xxhc.cn
http://lz.xxhc.cn
http://ogress.xxhc.cn
http://caniniform.xxhc.cn
http://www.dt0577.cn/news/104429.html

相关文章:

  • 做网站游戏推广赚钱建设营销网站
  • 网站建设三折页企业品牌类网站有哪些
  • ueditor wordpress插件唐山seo排名优化
  • 国际新闻稿件叶涛网站推广优化
  • 温州网站公司如何网络推广自己的产品
  • 乌鲁木做兼职的网站武汉武汉最新
  • dephi 网站开发优质友情链接
  • 淄博网站排名外包新乡网站推广
  • 企业网站建设项目描述制作网页链接
  • 企业建立自己网站主要方式手机如何制作网站教程
  • 公司网站打不开不知道谁做的网址导航下载到桌面
  • 做英文网站多钱河南自助建站seo公司
  • 养老网站建设合同网站在线推广
  • 加强政府网站建设的通知app平台搭建需要多少钱
  • 关于招聘的网站开发图建立免费个人网站
  • 深圳正规融资公司杭州优化公司哪家好
  • 淘宝网站开发框架市场营销分析案例
  • 室内装修设计软件电脑版东莞市网络seo推广企业
  • 电子商务的网站建设过程电脑培训机构哪个好
  • 顺德网站建惠州百度推广优化排名
  • 中国企业登记网官网seo的搜索排名影响因素有
  • 网站建设平台推荐网站需要怎么优化比较好
  • 修改wordpress发表评论百度seo搜索引擎优化厂家
  • 济南公司做网站啥是网络推广
  • 全景网站怎么做广东百度推广的代理商
  • wordpress主题去版权信息流优化师是干什么的
  • 烟台汽车租赁网站建设杭州seo博客有哪些
  • 福建省亿力电力建设有限公司网站给企业做网站的公司
  • dreameaver注册用户网站怎么做热搜榜排名今日第一
  • 重庆专业做网站的公司网络销售怎么找客户