mysql
依赖
mysql_async
是基于tokio2.0
的异步mysql
[dependencies]
mysql_async = "0.22.2"
tokio = "0.2.13"
database_url
,创建连接池DSN:mysql://root:[email protected]:3306/testdb?pool_min=10&pool_max=100&conn_ttl=10
?
后面的参数列表:
创建连接池
let pool = mysql_async::Pool::new(database_url);
从连接池获取一个connect,当离开作用域,调用drop自动返还给pool
let conn = pool.get_conn().await?;
程序退出,需要手动关闭连接池
pool.disconnect().await?;
1、ping,判断mysql服务器是否可用
let conn = conn.ping().await?;
2、query,普通的查询,需要自己判断sql参数是否正确
let result = conn.query("SELECT * FROM t_user").await?;
3、prep_exec,使用stmt语句查询
let result = conn.prep_exec("SELECT * FROM user where id = :id", params! {
"id" => 1
}).await?;
4、只查询一条结果集
let (conn, row): (_, Option) = conn.first_exec("SELECT * FROM user where id = :id", params! {
"id" => 1
}).await?;
5、执行sql,不关心result结果集
let conn = conn.drop_query(r"SET NAMES utf8").await?;
let conn = conn.drop_exec(r"SET NAMES utf8", ()).await?;
6、批量执行sql
// params是param!参数的集合
let conn = conn.batch_exec(r"INSERT INTO payment (customer_id, amount, account_name) VALUES (:customer_id, :amount, :account_name)", params).await?;
7、事务处理
let mut tr_opts = TransactionOptions::new();
tr_opts.set_isolation_level(IsolationLevel::RepeatableRead);
let tr = conn.start_transaction(tr_opts).await?;
let result: QueryResult<_, _> = tr.prep_exec("SELECT username, email FROM user where id = :id", params! {
"id" => 1
}).await?;
let (tr, user_info) = result.map_and_drop(|row| {
let username: Option = row.get("username");
let email: Option = row.get("email");
(username, email)
}).await?;
tr.commit().await?;
println!("{:?}", user_info);
1、使用mysql_async::from_row(),获取column的tuple结果
let result = conn.prep_exec("SELECT username, email FROM user where id = :id", params! {
"id" => 1
}).await?;
let (_, user_info) = result.map_and_drop(|row| {
let (username, email): (Option, Option) = mysql_async::from_row(row);
(username, email)
}).await?;
println!("{:?}", user_info);
2、使用row本身的函数get按照index索引,或者column的名字来获取
let result = conn.prep_exec("SELECT username, email FROM user where id = :id", params! {
"id" => 1
}).await?;
let (_, user_info) = result.map_and_drop(|row| {
let username: Option = row.get("username");
let email: Option = row.get("email");
(username, email)
}).await?;
println!("{:?}", user_info);
值类型
与rust类型对应关系Option
的None,int(0),“NULL”String
,Vec
,bool('0', '1')
,...(其他所有类型)
i8 ~ i128
,isize
,bool(0, 1)
u8 ~ u128
,usize
f32/64
Timespec
,NaiveDateTime
,NaiveDate
Duration
,NativeTime