You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Rust与sqlx向SQLite插入结构体时遇非空约束错误求助

解决SQLx插入数据时NOT NULL约束失败的问题

你遇到的NOT NULL constraint failed: refresh_keys.customer_id错误,核心原因是插入语句的占位符没有绑定实际参数,导致数据库接收到的customer_id值为NULL,违反了表的非空约束。

1. 准备要插入的有效数据实例

先创建或获取一个包含合法值的RefreshKeys实例:

let new_refresh_key = RefreshKeys {
    id: 1, // 若id是自增字段,可省略或留空(根据表结构调整)
    customer_id: 456, // 这里必须传入非空的合法值
    key: "generated-refresh-key-123".to_string(),
    enabled: true,
};

2. 绑定参数到SQL语句

使用.bind()方法为SQL中的每个占位符依次绑定对应字段的值:

rocket_db_pools::sqlx::query_as::<_, RefreshKeys>(
    "INSERT INTO refresh_keys (id, customer_id, key, enabled)
     VALUES (?1, ?2, ?3, ?4)"
)
.bind(new_refresh_key.id())
.bind(new_refresh_key.customer_id())
.bind(new_refresh_key.key())
.bind(new_refresh_key.enabled())
.fetch_one(&mut *db)
.await?

额外优化建议

如果你的id字段是数据库自增类型(比如SQLite的INTEGER PRIMARY KEY AUTOINCREMENT),建议修改插入语句,让数据库自动生成id值,避免手动赋值的冲突:

// 调整SQL语句,去掉id字段,添加RETURNING子句获取插入后的完整数据
rocket_db_pools::sqlx::query_as::<_, RefreshKeys>(
    "INSERT INTO refresh_keys (customer_id, key, enabled)
     VALUES (?1, ?2, ?3)
     RETURNING id, customer_id, key, enabled"
)
.bind(new_refresh_key.customer_id())
.bind(new_refresh_key.key())
.bind(new_refresh_key.enabled())
.fetch_one(&mut *db)
.await?

内容的提问来源于stack exchange,提问作者RuboGubo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 23:19:58