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

Python中如何实现类似PHP include()的功能?跨文件调用数据库连接

Python 中实现类似 PHP include() 的功能及跨文件夹调用数据库连接

Python 中没有和 PHP include() 完全一致的语法,但模块导入机制可以实现相同的效果,而且更符合Python的模块化规范。针对你分文件夹管理数据库连接和查询代码的需求,具体实现步骤如下:

一、调整文件结构

假设你最终的项目结构如下:

project/
├── db/
│   ├── __init__.py  # 空文件,标记为Python包
│   └── connection.py  # 数据库连接代码
└── queries/
    ├── __init__.py  # 空文件,标记为Python包
    └── fetch_emails.py  # 查询代码

二、优化数据库连接文件

推荐将连接逻辑封装为函数(比直接暴露变量更健壮,避免连接失效后无法复用),修改 db/connection.py:

import mysql.connector
from mysql.connector import errorcode

def get_db_connection():
    """获取数据库连接"""
    try:
        connection = mysql.connector.connect(
            host='localhost', 
            port=3307, 
            user='root', 
            password='', 
            database='amic'
        )
        print("Database connection made!")
        return connection
    except mysql.connector.Error as error:
        if error.errno == errorcode.ER_BAD_DB_ERROR:
            print("Database doesn't exist")
        elif error.errno == errorcode.ER_ACCESS_DENIED_ERROR:
            print("User name or password is wrong")
        else:
            print(error)
        return None

如果坚持使用原代码中的全局变量,也可以保留,但需注意连接状态的有效性:

# db/connection.py
import mysql.connector
from mysql.connector import errorcode

db_connection = None

try:
    db_connection = mysql.connector.connect(
        host='localhost', 
        port=3307, 
        user='root', 
        password='', 
        database='amic'
    )
    print("Database connection made!")
except mysql.connector.Error as error:
    if error.errno == errorcode.ER_BAD_DB_ERROR:
        print("Database doesn't exist")
    elif error.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("User name or password is wrong")
    else:
        print(error)

三、跨文件夹调用连接

方法1:临时添加项目根目录到Python路径

在 queries/fetch_emails.py 中,先将项目根目录加入Python可识别的路径,再导入连接模块:

import sys
import os

# 获取项目根目录路径
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(project_root)

# 导入连接函数(或变量)
from db.connection import get_db_connection

# 执行查询
db_connection = get_db_connection()
if db_connection:
    sql = 'SELECT * FROM email'
    cursor = db_connection.cursor()
    cursor.execute(sql)
    linhas = cursor.fetchall()
    
    # 处理查询结果(示例)
    for row in linhas:
        print(row)
    
    # 关闭资源
    cursor.close()
    db_connection.close()

方法2:将项目作为Python包运行

如果已经给每个文件夹添加了 __init__.py,可以直接用绝对导入,然后通过模块方式运行查询文件:

  1. queries/fetch_emails.py 代码:
from db.connection import get_db_connection

# 后续查询逻辑同上
  1. 在项目根目录(project/)下执行命令:
python -m queries.fetch_emails

关键说明

  • Python的import会执行目标模块的代码,并导入指定的变量/函数/类,这和PHP include()的核心作用一致,但Python的模块化机制更安全、更易维护。
  • 封装为函数的方式更推荐,因为如果连接意外断开,直接导入的全局变量会失效,而调用函数可以重新创建有效连接。

内容的提问来源于stack exchange,提问作者Victor Hugo Santos de Moraes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 18:25:37