rust tokio多线程异步查询sqlite数据库示例
Admin | 2023-3-10 21:43:08 | 被阅次数 | 1384
rust之tokio多线程异步查询sqlite数据库,代码如下。
use std::sync::{Mutex,Arc};
use std::thread;
use std::thread::sleep;
use std::time::Duration;
use serde_json::{Value};
use serde_json::json;
//下面这段是将数据库的连接设置为全局变量
use lazy_static::lazy_static;
lazy_static! {
static ref MYCON: Mutex<Connection> = {
let dbfile="MyDb/MyDb.db";
let mycn = Connection::open(dbfile).unwrap();
Mutex::new(mycn)
};
}
use rusqlite::{params, Connection, Result};
#[derive(Debug)]
struct Myinfor {
ID: String,
姓名: String,
}
#[tokio::main]
async fn main(){
let mut haddles = vec![];
for i in 1..=1000{
//println!("循环次数:{}",i);
let t = tokio::spawn(async move{
// let c = printinfor(i,format!("rust {}",i).as_str()).await;
// println!("第 {} 次异步",c);
let mut msg = json!({});
msg.as_object_mut().unwrap().insert("ID".to_string(), Value::String("666".to_string()));
let (b,rejson)=myget_examinfor(i,&msg,&MYCON.lock().unwrap());
});
haddles.push(t);
}
for t in haddles{
tokio::join!(t);
}
//下面这部分代码简单一点
// let t1 = tokio::spawn(async{
// let c1 = printinfor("rust1").await;
// println!("{}",c1);
// });
// let t2 = tokio::spawn(async{
// let c2 = printinfor("rust2").await;
// println!("{}",c2);
// });
// let _ = tokio::join!(t1,t2);
}
async fn printinfor(m:i32,s:&str) -> String{
//thread::sleep(Duration::from_millis(10000));
for k in 1..=1000000{
println!("当前线程是:{},循环变量:{}",m,k);
}
String::from(s)
}
fn myget_examinfor(m:i32,MyJson:&Value,con:&Connection)->(bool,Value){
let mut b:bool=false;
let sql:&str = "SELECT * from MyInfor where ID < ?";
let mut stmt = con.prepare(sql).unwrap();
let person_iterator = stmt.query_map(params![MyJson["ID"].as_str()], |row| {
Ok(Myinfor{
ID:row.get(0).unwrap(),
姓名:row.get(1).unwrap(),
})
}).unwrap();
let mut mystruct:Vec<Value>=Vec::new();
//p的内容如:Person { ID: "532627198109050546", name: "青山", sex: "男", tel: "13577699235" }
for p in person_iterator {
//println!("查询到每行的数据是:{:?}", &p.unwrap());//p.unwrap()
if let Ok(e) = p{
//print!("{} - {} \n",e.name,e.sex);
let mut TemJSon = json!({});
TemJSon.as_object_mut().unwrap().insert("ID".to_string(), Value::String(e.ID.to_string()));
TemJSon.as_object_mut().unwrap().insert("姓名".to_string(), Value::String(e.姓名.to_string()));
mystruct.push(TemJSon);
};
b=true;
}
println!("返回的Vec {:?}",mystruct);
let mut ReJSon = json!({}); //创建空json
ReJSon.as_object_mut().unwrap().insert("结果".to_string(), Value::Array(mystruct));
println!("返回的ReJSon {:?}",ReJSon);
println!("已完成第 {} 次----------------------------------------",m);
(b,ReJSon)
}