Python 如何简化MySQLdb connect的多次调用
我有以下MySQL连接:Python 如何简化MySQLdb connect的多次调用,python,mysql,reusability,Python,Mysql,Reusability,我有以下MySQL连接: import MySQLdb as mdb rbpdb = mdb.connect(host='db01.myhost.co.nl, user='pdbois', passwd='triplex', db='myxxx') 在编码过程中,我将在许多函数中多次重复使用此连接。 用于读取、创建和更新数据库 在不必多次调用上述代码段
import MySQLdb as mdb
rbpdb = mdb.connect(host='db01.myhost.co.nl,
user='pdbois',
passwd='triplex',
db='myxxx')
在编码过程中,我将在许多函数中多次重复使用此连接。
用于读取、创建和更新数据库
在不必多次调用上述代码段的情况下,实现该功能的最佳方法是什么?
我们可以把它作为类或函数放在单独的文件中吗?如果是这样的话,我们怎么称呼它呢?对我来说,有效的方法就是在一个单独的.py文件中创建一个模块,然后导入它,然后在任何脚本中使用MySQL连接 在这个文件中,您有一个连接的定义-例如MySQLdb或/和任何其他MySQL连接器。 我还使用mysql.connector
def connection(host, db, user, pass):
try:
import mysql.connector
connection_db = mysql.connector.connect(
user=user,
passwd=pass,
db=db,
host=host
)
return connection_db
except:
return None # or define here any other connection eg MySQLdb
然后您可以为每个DML操作定义一个函数,例如
def insert(host, db, user, pass, sql):
connection_db = connection(host, db, user, pass)
cursor = connection_db.cursor()
cursor.execute(sql)
connection_db.commit()
cursor.close()
connection_db.close()
最后,在脚本中添加以下内容就足够了:
import xxxxx.py
sql = """ INSERT INTO tbl (col1, col2) VALUES ('m','n'); """
var = xxxxx.insert(host, db, user, pass, sql)
你可以把它放在一个不同的类中,然后把它包含在你的其他文件中。