使用 Rust 語言連接操作 SQLite 資料庫,我使用 rusqlite 這個 crate,
看例子:
首先,使用 cargo 創建一個 Rust 專案,然后添加依賴 rusqlite:
![8
9
dependencies]
rusqtite = "
o. 26.3](https://img.uj5u.com/2022/01/22/297287220616011.png)
來到 main.rs,其余所有的代碼都寫在這里,
首先引入 rusqlite 相關的型別,并建立一個 Person struct:
![@ main.rs U X
src > @ main.rs > ?
1
2
3
4
5
6
7
8
use rusqlite :: {params,
?derive(Debug)]
struct Person {
id: i32,
name: String,
Connection ,
Result};
data: Option<Vec<u8>>,](https://img.uj5u.com/2022/01/22/297287220616012.png)
Person 有三個欄位,id、name 和 data,其實本例中,我們只會用到前兩個欄位,
下面,撰寫一個用來創建資料庫和 person 表的函式:

該函式會創建名為 data.db 的資料庫檔案(如果不存在的話),然后打開一個資料庫lian jie,并洗掉 person 表(如果存在的話),然后再建立一個 person 表,最后將 Connection 回傳,
接下來,我們再創建一個 insert_data 函式,它用來插入兩條資料,它使用 create_db 函式回傳的 Connection 的參考作為引數:
![fn insert_data(conn: &Connection) Result<()> {
Person {
let pl
id:
1,
"Dave" .to_string(),
name :
data: None,
Person {
let p2
id:
2,
"Nick" .
name :
data: None,
conn . execute(
"INSERT INTO person (id, name, data)
VALUES (?1, ?3),
params![pl.id, pl. name, pl. data, p2.id,
p2 . name,
p2.data],](https://img.uj5u.com/2022/01/22/297287220616014.png)
再創建一個可以從資料庫查詢資料的函式 get_data,它會回傳一個 Person 的 Vec:
![fn get_data(conn: 8Connection) Result<Vec<Person>> {
let
let
let
for
conn.prepare( "SELECT id, name, data from person")? ;
mut stmt
I rowl {
stmt . [ ] ,
persons _ iterator -
Ok(Person {
id: row. get(?)?,
name: row.get(l)?,
data: row.get(2)?,
mut persons = Vec :: new();
p in persons _ iterator {
persons . push(p?);
Ok(persons)](https://img.uj5u.com/2022/01/22/297287220616015.png)
最后,我們在 main 函式里依次呼叫這些函式,并把從資料庫讀取的資料進行列印:

運行結果:
![(base) solenovex@yangxus—MacBook—Pro—15 sqlite % cargo run
Compiling
Finished
Running
Person {
Person {
sqlite v0.1.0 (/Users/s01enovex/Projects/sq1ite)
dev [unoptimized + debuginfo] target(s) in 0.40s
Hi:
Hi:
target/ debug/sqlite
id: 1, name: "Dave" ,
id: 2, name:
"Nick" ,
data: None }
data: None }](https://img.uj5u.com/2022/01/22/297287220616017.png)

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/418089.html
標籤:其他
