当前位置:网站首页>Rust Web(三)—— 通过sqlx连接数据库(MySQL)
Rust Web(三)—— 通过sqlx连接数据库(MySQL)
2022-08-03 01:40:00 【仕上がりへ】
在学习了前辈所演示的 PostgreSQL连接方式后所进行的尝试;
通过这次尝试也能够进一步学习连接MySQL的其中一种方式;
除本文所使用的
sqlx连接方法外,还有其他的方式,诸如diesel,以后有机会在进行实践;
目录
Rust Web(三)—— 通过sqlx连接数据库(MySQL)
Rust Web(三)—— 通过sqlx连接数据库(MySQL)
一、环境准备
项目创建
在自己选择的目录下,创建一个(子)项目,此处命名为
db;在新建项目的
Cargo.toml文件内,添加所需要的依赖,具体如下:
[package]
name = "db"
version = "0.1.0"
edition = "2021"
[dependencies]
actix-rt="2.7.0"
actix-web="4.1.0"
dotenv = "0.15.0"
chrono = {version = "0.4.19", features = ["serde"]}
serde = {version = "1.0.140", features = ["derive"]}
sqlx = {version = "0.6.0", default_features = false, features = [
"mysql",
"runtime-tokio-rustls",
"macros",
"chrono",
]}注意:
在添加
crate时,注意使用版本要相互兼容,否则会出现编译警告:
The following warnings were discovered during the build. These warnings are an indication that the packages contain code that will become an error in a future release of Rust. These warnings typically cover changes to close soundness problems, unintended or undocumented behavior, or critical problems that cannot be fixed in a backwards-compatible fashion, and are not expected to be in wide use.
Each warning should contain a link for more information on what the warning means and how to resolve it.
To solve this problem, you can try the following approaches:
Some affected dependencies have newer versions available. You may want to consider updating them to a newer version to see if the issue has been fixed.
winapi v0.2.8 has the following newer versions available: 0.3.0, 0.3.1, 0.3.2, 0.3.3, 0.3.4, 0.3.5, 0.3.6, 0.3.7, 0.3.8, 0.3.9
If the issue is not solved by updating the dependencies, a fix has to be implemented by those dependencies. You can help with that by notifying the maintainers of this problem (e.g. by creating a bug report) or by proposing a fix to the maintainers (e.g. by creating a pull request):
Repository: GitHub - retep998/winapi-rs: Rust bindings to Windows API
Detailed warning command:
cargo report future-incompatibilities --id 1 --package [email protected]If waiting for an upstream fix is not an option, you can use the
[patch]section inCargo.tomlto use your own version of the dependency. For more information, see: Overriding Dependencies - The Cargo Book
具体需要访问
crates.io来查看合适的版本;而在版本兼容的的情况下,呈现的是以下结果:

连接请求
在根项目的目录下,新建名为
.env的文件,在文件内写入请求 URL;由于笔者所创建的项目是一个子项目,因此其位置位于所在根项目的目录之下;
DATABASE_URL=mysql://{user}:{password}@{IP}:{port}/{database name}二、数据库准备
笔者在此处选择的是过去在名为
test的数据库中的tt1表;内容如下:

三、功能实现
说明
首先简要说明一下本文所涉及 MySQL连接调用的 API
MySqlPoolOptions
new()


参考文档
sqlx::mysql - RustMySQL database driver.
https://docs.rs/sqlx/0.6.0/sqlx/mysql/index.html
代码实现
// extern crate chrono;
extern crate dotenv;
extern crate sqlx;
// use chrono::NaiveDateTime;
use dotenv::dotenv;
use sqlx::mysql::MySqlPoolOptions;
use std::env;
use std::io;
#[derive(Debug)]
pub struct Info {
pub ind: i32, // 数据库中将此字段设置为了主键
pub email: Option<String>, // 使用Option来处理潜在的空值情况
pub uid: Option<i32>,
pub reg_time: Option<i32>,
}
#[actix_rt::main]
async fn main() -> io::Result<()> {
dotenv().ok(); // 检测并读取.env文件中的内容,若不存在也会跳过异常
let database_url = env::var("DATABASE_URL")
.expect("Not configured in .env");
let db_pool = MySqlPoolOptions::new()
.connect(&database_url)
.await
.unwrap();
let tt1_rows = sqlx::query!(
r#"select ind,email,uid,regtime from tt1 where ind = ?"#,
6
)
.fetch_all(&db_pool)
.await
.unwrap();
let mut tt1_list = vec![];
for row in tt1_rows {
tt1_list.push(Info {
ind: row.ind.unwrap(),
email: row.email,
uid: row.uid,
reg_time: row.regtime,
})
}
println!("Info = {:?}", tt1_list);
Ok(())
}运行效果

每一个不曾起舞的日子,都是对生命的辜负。
边栏推荐
- 12-security退出.md
- 南瓜科学新品上线 开辟益智玩具新世界
- 孩子坐不住就是不专注?猿辅导揭秘专注力的三大误区
- 易购数码类电商商城网页设计与实现项目源码
- 【Flink】使用arthas在线诊断flink的那些事
- The cornerstone of high concurrency: multithreading, daemon threading, thread safety, thread synchronization, mutual exclusion lock, all in one article!...
- 8-jwt工具类
- The Multiversity 的 “非常重要的生命体” NFT 推出
- 【SQL】—数据库操作、表操作
- 五大靠谱的婚恋相亲APP详细特点缺点分析!
猜你喜欢

数据中台建设(八):数据服务体系建设

怎么从零编写一个 v3 版本的 chrome 浏览器插件实现 CSDN 博客网站的暗黑和明亮主题切换?

.NET in-depth analysis of the LINQ framework (four: IQueryable, IQueryProvider interface details)

作业8.2 线程同步互斥机制——互斥锁

优秀的 Verilog/FPGA开源项目总结及交流群

qt opengl 使用不同的颜色绘制线框三角形

Violent recursion to dynamic programming 06 (the sword refers to Offer II 095. Longest common subsequence)

国标GB28181协议EasyGBS平台项目现场通知消息过多导致系统卡顿该如何解决?

JSP第一篇 -----JSP九大内置对象(隐式对象)和四大域对象

The Multiversity 的 “非常重要的生命体” NFT 推出
随机推荐
怎么做postgrsql主备?
无法启动服务 错误 193 0xc1
有趣简单的M2处理器性能实验:Swift与C代码执行速度的比较
扩展卡尔曼滤波【转】
什么情况下DigiCert证书会引起发生安全警报?
46LVS+Keepalived群集
async-await
大厂标配 | 百亿级并发系统设计 | 学完薪资框框涨
新库上线 | CnOpenDataA股上市公司董监高信息数据
initramfs详解----设备文件系统
php一维数组合并
Greenplum数据库故障分析——can not listen port
怎么从零编写一个 v3 版本的 chrome 浏览器插件实现 CSDN 博客网站的暗黑和明亮主题切换?
7-Redis工具类
MySQL删库不跑路
能添加任意贴图超级复布局的初级智能文本提示器
PHICOMM(斐讯)N1盒子 - recovery模式救砖卡登录页LOGO卡1%卡4%卡26%
js垃圾回收机制
【社媒营销】Facebook速推帖子如何运作?值得吗?
高并发基石:多线程、守护线程、线程安全、线程同步、互斥锁,一文扫尽!...