我的 Web 应用程序有一个通过 Rocket 的 REST API,连接到 MySQL 数据库,并且有一个端点。我无法弄清楚如何访问控制器内部的数据库连接:
#![feature(decl_macro)]
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate rocket_contrib;
use rocket_contrib::json::Json;
use serde::Serialize;
#[macro_use]
extern crate mysql;
use mysql as my;
use mysql::consts::ColumnType::MYSQL_TYPE_DATE;
use mysql::prelude::Queryable;
use mysql::Pool;
#[get("/orgs")]
fn get_orgs(conn: MyDb) -> Json<Vec<Org>> {
// I need to have the db connection here to pass it to get_all.
let o = match Org::get_all() {
Ok(o) => o,
Err(e) => panic!(e),
};
Json(o)
}
#[derive(Serialize)]
pub struct Org {
pub id: Option<i32>,
pub name: String,
}
fn main() {
let url = "mysql://root:mysql@(localhost:33061)/somedb";
let pool = Pool::new(url)?;
let mut conn = pool.get_conn();
// I need to pass "conn" around, first to get_orgs, then to Org::get_all.
rocket::ignite().mount("/", routes![get_orgs]).launch();
}
impl Org {
fn get_all(mut conn: mysql::Conn) -> Result<Vec<Org>, Err> {
let all_orgs = conn.query_map("SELECT id, name from organization", |(id, name)| Org {
id,
name,
})?;
return match all_orgs() {
Ok(all_orgs) => all_orgs,
Err(e) => e,
};
}
}
我的假设是#[get("/orgs")]
会生成一堆代码。我发现了这个:https ://rocket.rs/v0.4/guide/state/#databases - 看起来是正确的,但我无法找到一个通过连接字符串连接到我的 MySQL 实例的工作示例。
这是我的依赖项:
[dependencies]
rocket = "0.4.2"
rocket_codegen = "0.4.2"
rocket_contrib = "0.4.2"
serde = {version = "1.0", features = ["derive"]}
serde_json = {version = "1.0"}
mysql = "*"
如何建立 MySQL 连接并传递它?