# sqlite3.OperationalError: 无法打开数据库：/path/to/attached.db

- **ID:** `database/sqlite-cannot-attach-database`
- **领域:** database
- **类别:** config_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

ATTACH DATABASE 命令失败，因为目标数据库文件不存在、不可读、目录不可写（用于创建新数据库），或文件被另一个进程锁定。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| SQLite 3.36 | active | — | — |
| SQLite 3.40 | active | — | — |
| SQLite 3.45 | active | — | — |
| SQLite 3.46 | active | — | — |

## 解决方案

1. ```
   检查文件是否存在：`ls -la /path/to/attached.db`。如果不存在，创建一个空数据库文件：`touch /path/to/attached.db` 并确保正确的权限：`chmod 644 /path/to/attached.db`。然后重试 ATTACH 命令：`ATTACH DATABASE '/path/to/attached.db' AS attached_db;`
   ```
2. ```
   使用 `lsof /path/to/attached.db` 等工具检查是否有其他进程锁定了该文件。如果是，杀死或等待该进程释放锁，或使用不同的数据库文件路径。
   ```
3. ```
   确保父目录可写：`chmod 755 /path/to` 并且文件不在只读文件系统中。如果使用 NFS，检查 NFS 锁问题并考虑使用本地文件路径。
   ```

## 无效尝试

- **Set the file permissions to 777 recursively on the directory** — Overly permissive permissions can cause security issues and may not solve the problem if the file is locked by another process (50% 失败率)
- **Use ATTACH DATABASE with a different alias expecting it to create the file** — ATTACH DATABASE can create a new database file only if the directory is writable; if the error is due to a locked file, a new alias won't help (40% 失败率)
- **Restart the application to release locks** — If the lock is held by another process (e.g., a separate application instance), restarting your app won't release that lock (60% 失败率)
