11.1.1.1. 创建 SQLite 数据库

rusqlite-badge cat-database-badge

使用 rusqlite crate 打开 SQLite 数据库连接。Windows 上编译 rusqlite crate 请参考文档

如果数据库不存在,Connection::open 方法将创建它。

use rusqlite::{Connection, Result};
use rusqlite::NO_PARAMS;

fn main() -> Result<()> {
    let conn = Connection::open("cats.db")?;

    conn.execute(
        "create table if not exists cat_colors (
             id integer primary key,
             name text not null unique
         )",
        NO_PARAMS,
    )?;
    conn.execute(
        "create table if not exists cats (
             id integer primary key,
             name text not null,
             color_id integer not null references cat_colors(id)
         )",
        NO_PARAMS,
    )?;

    Ok(())
}