Spaces:
Paused
Paused
File size: 2,500 Bytes
2fd3032 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | """
测试 SQLite 数据库连接
"""
import asyncio
import aiosqlite
import os
async def test_sqlite():
"""测试 SQLite 数据库"""
print("=" * 50)
print("SQLite 数据库测试")
print("=" * 50)
print()
db_path = "bot.db"
try:
# 连接数据库
print(f"正在连接到数据库: {db_path}")
conn = await aiosqlite.connect(db_path)
# 启用外键
await conn.execute("PRAGMA foreign_keys = ON")
await conn.execute("PRAGMA journal_mode = WAL")
print("✅ 连接成功!")
print()
# 创建测试表
print("创建测试表...")
await conn.execute("""
CREATE TABLE IF NOT EXISTS test_table (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
await conn.commit()
print("✅ 表创建成功")
print()
# 插入数据
print("插入测试数据...")
await conn.execute("INSERT INTO test_table (name) VALUES (?)", ("test_user",))
await conn.commit()
print("✅ 数据插入成功")
print()
# 查询数据
print("查询数据...")
cursor = await conn.execute("SELECT * FROM test_table")
rows = await cursor.fetchall()
for row in rows:
print(f" ID: {row[0]}, Name: {row[1]}, Created: {row[2]}")
print("✅ 查询成功")
print()
# 获取最后插入的 ID
cursor = await conn.execute("SELECT last_insert_rowid()")
row = await cursor.fetchone()
print(f"最后插入的 ID: {row[0]}")
print()
# 清理
await conn.execute("DROP TABLE test_table")
await conn.commit()
print("✅ 测试数据已清理")
print()
# 关闭连接
await conn.close()
print("=" * 50)
print("🎉 所有测试通过!SQLite 配置正确!")
print("=" * 50)
return True
except Exception as e:
print(f"❌ 测试失败: {e}")
import traceback
traceback.print_exc()
return False
if __name__ == "__main__":
result = asyncio.run(test_sqlite())
input("\n按回车键退出...")
|