Python 如何避免“写”字;MySQLdb.connect";一次又一次?

Python 如何避免“写”字;MySQLdb.connect";一次又一次?,python,mysql,Python,Mysql,我想知道是否有办法避免写入MySQLdb.connect(host='localhost',user='xyz',password='xyz',db='xyz') 用Python一次又一次地 例如: def Add_New_User(self): self.db = MySQLdb.connect(host='localhost', user='xyz', password='xyz', db='xyz') self.cur = self.db.cursor() 在两行或三行之

我想知道是否有办法避免写入
MySQLdb.connect(host='localhost',user='xyz',password='xyz',db='xyz')
用Python一次又一次地

例如:

def Add_New_User(self):
    self.db = MySQLdb.connect(host='localhost', user='xyz', password='xyz', db='xyz')
    self.cur = self.db.cursor()
在两行或三行之后(当需要新的
def
并且需要大量
def
时),我需要多次重新写入相同的字符串

def Add_New_User(self):
    self.db = MySQLdb.connect(host='localhost', user='xyz', password='xyz', db='xyz')
    self.cur = self.db.cursor()

我希望有一种简单的方法来调用它,比如编写并保存在中的连接代码,例如,
MyConString.py
,然后在新的
def
中,比如,
index.py
,我只需调用函数
MyConString

创建一个名为connection的函数:

def conn(database):
    import mysql.connector
    connection = mysql.connector.connect(host='localhost',
                                         database=database,
                                         user='root',
                                         password='yourpass')
    cursor = connection.cursor(buffered=True)
    return connection, cursor
现在,无论何时您必须在任何功能中连接,请执行以下操作:

def insert():
    connection_data = conn("mydatabase")
    connection = connection_data[0]
    cursor = connection_data[1]
    cursor.execute("show tables;")
    connection.commit()
    connection.close()
您甚至可以为重复使用以保持主文件干净的函数创建一个全新的脚本。 然后,只需添加import connections.py(即包含conn()函数的文件名)


希望这有帮助

你已经回答了你自己的问题。创建一个运行这两行的函数,并在任何需要的地方调用它。。。
# This is your main.py
import connections
def insert():
    connection_data = connections.conn("mydatabase")
    connection = connection_data[0]
    cursor = connection_data[1]
    cursor.execute("show tables;")
    connection.commit()
    connection.close()