Home > Software design >  Python expression equivalent to include() of PHP
Python expression equivalent to include() of PHP

Time:09-26

Is there any expression in Python that is equivalent to 'include()' of PHP?

To be more specific, I want to make in python a file for database connection and another for queries, but the variable for the connection only exists in the connection file. If it was in PHP I could use 'include()' to call the connection variable in another file. The codes in Python are these (both are in the same folder):

Connection:

    import mysql.connector
from mysql.connector import errorcode
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)

Query:

sql = 'SELECT * FROM email'
cursor = db_connection.cursor()
cursor.execute(sql)
linhas = cursor.fetchall();

Separating these two codes into two distinct folders, I'll need the 'db_connection' variable to execute the query, therefore, I'll need to call it in the query's folder. How could I do this?

CodePudding user response:

In your query file you can import db_connection from your connection file using:

from <your_connection_file> import db_connection

and then use db_connection the way you want.

  • Related