定制软件开发Rust Web(三)—— 通过sqlx连接数据库(MySQL)

  • 定制软件开发在学习了前辈所演示的 定制软件开发连接方式后所进行的尝试;

  • 定制软件开发通过这次尝试也能够进定制软件开发一步学习连接MySQL的其中一种方式;

  • 除本文所使用的sqlx连接方法外,还有其他的方式,诸如diesel,以后有机会在进行实践;

目录


Web(三)—— 通过sqlx连接数据库(MySQL)

一、环境准备


项目创建

  • 在自己选择的目录下,创建一个(子)项目,此处命名为 db

  • 在新建项目的 Cargo.toml 文件内,添加所需要的依赖,具体如下:

  1. [package]
  2. name = "db"
  3. version = "0.1.0"
  4. edition = "2021"
  5. [dependencies]
  6. actix-rt="2.7.0"
  7. actix-web="4.1.0"
  8. dotenv = "0.15.0"
  9. chrono = {version = "0.4.19", features = ["serde"]}
  10. serde = {version = "1.0.140", features = ["derive"]}
  11. sqlx = {version = "0.6.0", default_features = false, features = [
  12. "mysql",
  13. "runtime-tokio-rustls",
  14. "macros",
  15. "chrono",
  16. ]}

注意:

  • 在添加 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):

    • winapi@0.2.8

    • Repository:

    • Detailed warning command: cargo report future-incompatibilities --id 1 --package winapi@0.2.8

  • If waiting for an upstream fix is not an option, you can use the [patch] section in Cargo.toml to use your own version of the dependency. For more information, see:

  • 具体需要访问crates.io 来查看合适的版本;

  • 而在版本兼容的的情况下,呈现的是以下结果:

 

连接请求

  • 根项目的目录下,新建名为 .env 的文件,在文件内写入请求 URL;

  • 由于笔者所创建的项目是一个子项目,因此其位置位于所在根项目的目录之下;

DATABASE_URL=mysql://{user}:{password}@{IP}:{port}/{database name}

二、数据库准备


  • 笔者在此处选择的是过去在名为 test的数据库中的 tt1表;

  • 内容如下:

 

三、功能实现


说明

  • 首先简要说明一下本文所涉及 MySQL连接调用的 API

    • MySqlPoolOptions

      • new()

 

参考文档

代码实现

  1. // extern crate chrono;
  2. extern crate dotenv;
  3. extern crate sqlx;
  4. // use chrono::NaiveDateTime;
  5. use dotenv::dotenv;
  6. use sqlx::mysql::MySqlPoolOptions;
  7. use std::env;
  8. use std::io;
  9. #[derive(Debug)]
  10. pub struct Info {
  11.    pub ind: i32, // 数据库中将此字段设置为了主键
  12.    pub email: Option<String>, // 使用Option来处理潜在的空值情况
  13.    pub uid: Option<i32>,
  14.    pub reg_time: Option<i32>,
  15. }
  16. #[actix_rt::main]
  17. async fn main() -> io::Result<()> {
  18.    dotenv().ok(); // 检测并读取.env文件中的内容,若不存在也会跳过异常
  19.    let database_url = env::var("DATABASE_URL")
  20.       .expect("Not configured in .env");
  21.    let db_pool = MySqlPoolOptions::new()
  22.       .connect(&database_url)
  23.       .await
  24.       .unwrap();
  25.    let tt1_rows = sqlx::query!(
  26.        r#"select ind,email,uid,regtime from tt1 where ind = ?"#,
  27.        6
  28.   )
  29.       .fetch_all(&db_pool)
  30.       .await
  31.       .unwrap();
  32.    let mut tt1_list = vec![];
  33.    for row in tt1_rows {
  34.        tt1_list.push(Info {
  35.            ind: row.ind.unwrap(),
  36.            email: row.email,
  37.            uid: row.uid,
  38.            reg_time: row.regtime,
  39.       })
  40.   }
  41.    println!("Info = {:?}", tt1_list);
  42.    Ok(())
  43. }

运行效果

 

每一个不曾起舞的日子,都是对生命的辜负。

网站建设定制开发 软件系统开发定制 定制软件开发 软件开发定制 定制app开发 app开发定制 app开发定制公司 电商商城定制开发 定制小程序开发 定制开发小程序 客户管理系统开发定制 定制网站 定制开发 crm开发定制 开发公司 小程序开发定制 定制软件 收款定制开发 企业网站定制开发 定制化开发 android系统定制开发 定制小程序开发费用 定制设计 专注app软件定制开发 软件开发定制定制 知名网站建设定制 软件定制开发供应商 应用系统定制开发 软件系统定制开发 企业管理系统定制开发 系统定制开发