如何在另一个脚本中调用file1.py中的conn_db数据库连接函数?
Question
I've defined a pre-configured database connection function in
file1.pywith the following code:def conn_db(): try: cursor = pymysql.cursors.DictCursor conn = pymysql.connect(host=settings.host, user=settings.user, password=settings.password, db=settings.database, port=settings.port, cursorclass=cursor) dbcursor = conn.cursor() except pymysql.err.OperationalError as e: print("Unable to make a connection to the mysql database. \n Error was:{}".format(e)) return conn, dbcursorHow can I call this
conn_db()function from another Python script?
Answer
Hey there! Calling your conn_db() function from another script is straightforward—here's how to do it properly, with some key best practices to avoid headaches later:
1. Ensure your files are accessible
First, make sure the script you want to use (let's say it's file2.py) is in the same directory as file1.py. If they're in different folders, you'll need to adjust Python's import path (more on that later), but let's start with the simplest scenario.
2. Import and use the function
In file2.py, import the conn_db function directly from file1 and call it to get your database connection and cursor:
# Import the connection function from file1 from file1 import conn_db # Call the function to retrieve connection and cursor objects db_connection, db_cursor = conn_db() # Example: Use the cursor to run a query try: db_cursor.execute("SELECT * FROM your_target_table") query_results = db_cursor.fetchall() print("Query results:", query_results) finally: # Critical: Always close connections/cursors when finished to avoid leaks db_cursor.close() db_connection.close()
3. Add error handling (don't skip this!)
Your current conn_db() function catches connection errors but still returns conn and dbcursor—which could be None if the connection failed. Add a check in your calling script to prevent crashes:
from file1 import conn_db conn, cursor = conn_db() # Verify the connection was successful before proceeding if conn and cursor: try: cursor.execute("SELECT 1") # Quick test query print("Database connection established successfully!") except Exception as e: print(f"Query failed: {str(e)}") finally: cursor.close() conn.close() else: print("Could not connect to the database—check your settings or credentials.")
4. Handling files in different directories
If file1.py lives in a subfolder (e.g., database_utils/file1.py), you have two easy options:
- Add an empty
__init__.pyfile in the subfolder to mark it as a Python package, then import like this:from database_utils.file1 import conn_db - Or temporarily add the folder path to Python's system path before importing:
import sys import os # Add the parent folder of file1 to Python's path sys.path.append(os.path.abspath("path/to/folder-containing-file1")) from file1 import conn_db
That's all you need! Just remember to manage your database connections responsibly to avoid leaving open connections hanging around.
内容的提问来源于stack exchange,提问作者John

