当前位置:网站首页>[rust web rokcet Series 2] connect the database and add, delete, modify and check curd
[rust web rokcet Series 2] connect the database and add, delete, modify and check curd
2022-07-02 01:18:00 【Macaroni candy】
Rust Web Rokcet series 2 Connect to database and CURD Additions and deletions
original text : https://www.ftls.xyz/posts/rust-rocket2/
author : Macaroni candy
Series address : https://www.ftls.xyz/series/rust-web-rokcet
It uses SQLite database , In fact, all kinds of databases are similar . There are already many packages to help us deal with various details . at present diesel Support mysql,postgres and sqlite. Functions are generally used when the mouse moves over the function , In the displayed document . let me put it another way , stay Ctrl+ left-click Click in to display the source file between the lines .
The related documents :
https://rocket.rs/v0.5-rc/guide/state/#databases
Reference writing :
https://github.com/SergioBenitez/Rocket/tree/v0.5-rc/examples/databases
Installation tools SQLite and diesel_cli
Introduce to you Windows SQLite Lower installation method , open SQLite Official website Download page .
https://www.sqlite.org/download.html
choice Precompiled Binaries for Windows
64 Bit machine download sqlite-dll-win64-x64-3370200.zip and sqlite-tools-win32-x86-3370200.zip
32 Bit machine download sqlite-dll-win32-x86-3370200.zip and sqlite-tools-win32-x86-3370200.zip
Unzip all the files in these two packages to a directory , And use Microsoft Generation tool , Execute... In the directory
lib /def:sqlite3.def /machine:X64 /out:sqlite3.lib
Then add the directory to the environment variable , Then open the terminal to execute :
cargo install diesel_cli --no-default-features --features sqlite
To write SQL
open Project directory , perform
diesel setup
diesel migration generate article
Generated migrations\2022-02-14-114903_article\up.sql and migrations\2022-02-14-114903_article\down.sql
Then write up.sql and down.sql
migrations\2022-02-11-063903_product\up.sql
-- Your SQL goes here
CREATE TABLE article (
id INTEGER NOT NULL PRIMARY KEY,
title Text NOT NULL,
author Text NOT NULL,
content Text NOT NULL,
created_at Text NOT NULL
)
migrations\2022-02-14-114903_article\down.sql
-- This file should undo anything in `up.sql`
DROP TABLE article;
Create project root , and Cargo.toml At the same level . establish .env file . write in
.env
DATABASE_URL=article.db
And then execute
diesel migration run
diesel It will automatically create one article.db, This is the database we will use later . besides , also src\schema.rs and diesel.toml file .
Use database tools , You can see that a table has been successfully created

Add dependency
stay Cargo.toml Add dependency to
Cargo.toml
[package]
name = "teach_used"
version = "0.1.0"
edition = "2021"
authors = ["Kkbt <[email protected]>"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rocket = { version = "0.5.0-rc.1",features = ["json"]}
diesel = "1.4.8"
[dependencies.rocket_sync_db_pools]
version = "0.1.0-rc.1"
default-features = false
features = ["diesel_sqlite_pool"]
establish Rocket.toml
Rocket.toml
[global.databases]
sqlite_main = { url = "article.db" }
And then in main.rs Join the database connection , The connection pool is enabled by default .
#[macro_use]
extern crate diesel;
use rocket_sync_db_pools::database;
#[database("sqlite_main")]
pub struct MainDbConn(diesel::SqliteConnection);
Actually rocket_sync_db_pools::diesel It's also available . Be similar to
use rocket_sync_db_pools::{
database,diesel};
#[database("sqlite_main")]
pub struct MainDbConn(diesel::SqliteConnection);
But I haven't figured out how to import #[macro_use] , The macro in src\schema.rs in table Yes . Let me know if anyone knows . Such should not be introduced diesel = “1.4.8” Rely on .
CURD
And then modify src\main.rs,src\module.rs,src\routes.rs .
src\main.rs :
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate diesel;
mod module;
mod routes;
mod schema;
use rocket_sync_db_pools::database;
use routes::*;
#[database("sqlite_main")]
pub struct MainDbConn(diesel::SqliteConnection);
#[launch]
fn rocket() -> _ {
rocket::build()
// database
.attach(MainDbConn::fairing())
.mount("/", routes![index])
// add api
.mount("/", routes![get_all_articles, get_article_by_id])
.mount("/", routes![post_article, put_article])
.mount("/", routes![delete_all_articles, delete_article])
}
src\module.rs
use crate::schema::article;
use diesel::Insertable;
use rocket::serde::{
Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone, Debug, Queryable, Insertable)]
#[serde(crate = "rocket::serde")]
#[table_name = "article"]
pub struct Article {
pub id: i32,
pub title: String,
pub author: String,
pub content: String,
pub created_at: String,
}
#[derive(Debug, Serialize, Deserialize, Queryable, Clone, Insertable, AsChangeset)]
#[serde(crate = "rocket::serde")]
#[table_name = "article"]
pub struct PostArticle {
pub title: String,
pub author: String,
pub content: String,
pub created_at: String,
}
src\routes.rs It's simple CURD , See the documentation for details . Functions are generally used when the mouse moves over the function , In the displayed document . let me put it another way , stay Ctrl+ left-click Click in to display the source file between the lines .
use diesel::{
prelude::*, QueryDsl, RunQueryDsl};
use rocket::serde::json::{
serde_json::json, Json, Value};
use rocket::{
delete, get, post, put, response::status::Created, response::Debug};
use crate::module::{
Article, PostArticle};
use crate::schema::article;
use crate::MainDbConn;
type Result<T, E = Debug<diesel::result::Error>> = std::result::Result<T, E>;
#[get("/")]
pub fn index() -> Value {
json!({
"kkbt":"Hello, world!"})
}
// check all
#[get("/article")]
pub async fn get_all_articles(db: MainDbConn) -> Result<Json<Vec<Article>>> {
let all = db
.run(move |conn| article::table.load::<Article>(conn))
.await?;
Ok(Json(all))
}
// check by id
#[get("/article/<in_id>")]
pub async fn get_article_by_id(db: MainDbConn, in_id: i32) -> Option<Json<Article>> {
db.run(move |conn| article::table.filter(article::id.eq(in_id)).first(conn))
.await
.map(Json)
.ok()
}
// increase
#[post("/article", format = "json", data = "<in_article>")]
pub async fn post_article(
db: MainDbConn,
in_article: Json<PostArticle>,
) -> Result<Created<Json<PostArticle>>> {
let article_in = in_article.clone();
db.run(move |conn| {
diesel::insert_into(article::table)
.values(&article_in)
.execute(conn)
})
.await?;
Ok(Created::new("/").body(in_article))
}
// Change by id
#[put("/article/<in_id>", format = "json", data = "<in_article>")]
pub async fn put_article(
db: MainDbConn,
in_id: i32,
in_article: Json<PostArticle>,
) -> Result<Option<()>> {
let affected = db
.run(move |conn| {
diesel::update(article::table.filter(article::id.eq(in_id)))
.set(in_article.into_inner())
.execute(conn)
})
.await?;
Ok((affected == 1).then(|| ()))
}
// Delete by id
#[delete("/article/<in_id>")]
pub async fn delete_article(db: MainDbConn, in_id: i32) -> Result<Option<()>> {
let affected = db
.run(move |conn| {
diesel::delete(article::table)
.filter(article::id.eq(&in_id))
.execute(conn)
})
.await?;
Ok((affected == 1).then(|| ()))
}
// Delete all
#[delete("/article/all")]
pub async fn delete_all_articles(db: MainDbConn) -> Result<()> {
db.run(move |conn| diesel::delete(article::table).execute(conn))
.await?;
Ok(())
}
test
Postman JSON Format shared links :
https://www.getpostman.com/collections/46d782fa07ef766822f6
If the link fails , Please contact me . Only one sound .
边栏推荐
- NeRV: Neural Reflectance and Visibility Fields for Relighting and View Synthesis
- 关于ASP.NET CORE使用DateTime日期类型参数的一个小细节
- Global and Chinese markets for distributed generation and energy storage in telecommunications networks 2022-2028: Research Report on technology, participants, trends, market size and share
- Global and Chinese markets for freight and logistics 2022-2028: Research Report on technology, participants, trends, market size and share
- Day 13 of hcip (relevant contents of BGP agreement)
- Entrepreneurship is a little risky. Read the data and do a business analysis
- Keepalived introduction and installation
- XMind思维导图
- 只是以消费互联网的方式和方法来落地和实践产业互联网,并不能够带来长久的发展
- Leetcode, 3 repeatless longest subsequence
猜你喜欢

Data visualization in medical and healthcare applications
![[IVX junior engineer training course 10 papers to get certificates] 0708 news page production](/img/ad/a1cb672d2913b6befd6d8779c993ec.jpg)
[IVX junior engineer training course 10 papers to get certificates] 0708 news page production

Review notes of compilation principles

Edge extraction edges based on Halcon learning_ image. Hdev routine

教你白嫖Amazon rds一年并搭建MySQL云数据库(只需10分钟,真香)

Datawhale 社区黑板报(第1期)

Edge computing accelerates live video scenes: clearer, smoother, and more real-time

Entrepreneurship is a little risky. Read the data and do a business analysis

MySQL application day02

How can I batch produce the same title for the video?
随机推荐
Basic usage of shell script
cookie、session、tooken
Learning note 24 - multi sensor post fusion technology
969 interlaced string
How does schedulerx help users solve the problem of distributed task scheduling?
Excel PivotTable
The 8-year salary change of testers makes netizens envy it: you pay me one year's salary per month
Comprehensive broadcast of global and Chinese markets 2022-2028: Research Report on technology, participants, trends, market size and share
首场“移动云杯”空宣会,期待与开发者一起共创算网新世界!
[eight sorts ④] merge sort, sort not based on comparison (count sort, cardinal sort, bucket sort)
Variables and constants of go language foundation
How can programmers better plan their career development?
Global and Chinese markets for power over Ethernet (POE) solutions 2022-2028: Research Report on technology, participants, trends, market size and share
[eight sorts ②] select sort (select sort, heap sort)
I'll teach you to visit Amazon RDS for a year and build a MySQL cloud database (only 10 minutes, really fragrant)
The first "mobile cloud Cup" empty publicity meeting, looking forward to working with developers to create a new world of computing!
[IVX junior engineer training course 10 papers] 02 numerical binding and adaptive website production
Han Zhichao: real time risk control practice of eBay based on graph neural network
Global and Chinese market of aircraft MRO software 2022-2028: Research Report on technology, participants, trends, market size and share
Entrepreneurship is a little risky. Read the data and do a business analysis