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

Discord机器人集成SQLite3后无法找到数据库文件求助

问题:SQLite3数据库文件本地目录不可见,但读写功能正常

我在Discord机器人中集成了SQLite3,能正常提交数据到数据库、执行查询并获取结果,但在项目本地目录里看不到数据库文件本身。我试过把数据库位置记录到日志文件里,也没效果。请问我哪里漏了?

更新

截图1
截图2

当前使用的函数

def add_replay_to_db(filename: str, gamejson: str, playerjson: str, resultjson: str, replaysource: str, messageauthor: str, md5: str):
    try:
        db_path = '/database/yesman.db'

        # Ensure the directory exists
        if not os.path.exists(os.path.dirname(db_path)):
            fullpath = os.path.dirname(db_path)
            os.makedirs(fullpath)
            logger.info(f'Database created: {fullpath}')


        logger.info(f'Adding {filename} to the SQL database')

        connection = sqlite3.connect(db_path)
        cursor = connection.cursor()

        cursor.execute('''CREATE TABLE IF NOT EXISTS replay_raw_data (
                            id INTEGER PRIMARY KEY,
                            filename TEXT,
                            game_json TEXT,
                            player_json TEXT,
                            result_json TEXT,
                            replay_source TEXT,
                            user TEXT,
                            md5 TEXT
                          )''')

        # INSERT INTO
        cursor.execute('INSERT INTO replay_raw_data (filename, game_json, player_json, result_json, replay_source, user, md5) VALUES (?, ?, ?, ?, ?, ?, ?)',
                       (str(filename), str(gamejson), str(playerjson), str(resultjson), str(replaysource), str(messageauthor), str(md5)))

        connection.commit()

        # Fetch and print data
        cursor.execute('SELECT * FROM replay_raw_data')
        rows = cursor.fetchall()
        for row in rows:
            print(row)

    except sqlite3.Error as er:
            logger.error(f'{er}')

    finally:
        if connection:
            connection.close()

问题原因及解决办法

  • 核心问题:路径错误
    你写的db_path = '/database/yesman.db'是系统根目录下的绝对路径,数据库文件实际存在于系统根目录的database文件夹里,而非你的项目本地目录,所以在项目文件夹里找不到它。

  • 解决步骤

    1. 改用项目相对路径:把db_path改成./database/yesman.db或者database/yesman.db,这样会在你的项目根目录下创建database文件夹和对应的数据库文件。
    2. 用脚本目录拼接绝对路径(更稳妥):通过代码获取当前脚本所在的项目目录,再拼接数据库路径,避免路径混乱:
      import os
      # 获取当前脚本所在目录
      script_dir = os.path.dirname(os.path.abspath(__file__))
      # 拼接数据库路径
      db_path = os.path.join(script_dir, 'database', 'yesman.db')
      
    3. 添加路径日志排查:在连接数据库前,把完整的db_path输出到日志,确认数据库实际位置:
      logger.info(f'数据库实际路径:{db_path}')
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 04:32:31