使用Rusqlite操作sqlite数据库
[dependencies]rusqlite = "0.22.0"use rusqlite::{params, Connection, Result};#[derive(Debug)]struct Person {id: i32,name: String,}fn main() {let con = Connection::open_in_memo...
·
[dependencies]
rusqlite = "0.22.0"
use rusqlite::{params, Connection, Result};
#[derive(Debug)]
struct Person {
id: i32,
name: String,
}
fn main() {
let con = Connection::open_in_memory().unwrap();
let flag1 = check_table_existed("table_1", &con);
if !flag1 {
create_table(&con);
}
if !check_person_existed("Tester1", &con) {
insert_person("Tester1", &con);
}
if !check_person_existed("Tester2", &con) {
insert_person("Tester2", &con);
}
list_persons(&con);
match con.close(){
Ok(v) => v,
Err(e) => panic!("{:?}", e),
};
}
fn check_table_existed(table_name : &str, con : &Connection) -> bool {
let sql: &str = "SELECT COUNT(`name`) FROM `sqlite_master` WHERE `type` = 'table' AND `name` = ?";
let mut stmt = con.prepare(sql).unwrap();
let rs = stmt.query_row(params![table_name], |row | {
return row.get(0) as Result<i32>;
});
let count = rs.unwrap();
return count > 0;
}
fn create_table(con : &Connection) {
let sql : &str = "CREATE TABLE IF NOT EXISTS `table_1`(`Id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `Name` TEXT NOT NULL)";
match con.execute(sql, params![]) {
Ok(o) => o,
Err(e) => panic!("{:?}", e),
};
}
fn check_person_existed(person: &str, con: &Connection) -> bool {
let sql: &str = "SELECT COUNT(`Id`) FROM `table_1` WHERE `Name` = ?";
let mut stmt = con.prepare(sql).unwrap();
let rs = stmt.query_row(params![person], |row|{
row.get(0) as Result<i32>
});
let count = rs.unwrap();
return count > 0;
}
fn insert_person(person: &str, con: &Connection) {
let sql: &str = "INSERT INTO `table_1`(`Name`) VALUES (?)";
match con.execute(sql, params![person]) {
Ok(o) => o,
Err(e) => panic!("{:?}", e),
};
}
fn list_persons(con : &Connection){
let sql:&str = "SELECT * FROM `table_1`";
let mut stmt = con.prepare(sql).unwrap();
let person_iterator = stmt.query_map(params![], |row| {
Ok(Person{
id: row.get(0).unwrap(),
name: row.get(1).unwrap(),
})
}).unwrap();
for p in person_iterator {
println!("{:?}", p.unwrap());
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)