我有以下MySQL连接:
import MySQLdb as mdb
rbpdb = mdb.connect(host='db01.myhost.co.nl,
user='pdbois',
passwd='triplex',
db='myxxx')在编写代码的过程中,我会在许多函数中多次重用这个连接。用于读取、创建和更新数据库。
在不多次调用上述代码片段的情况下,实现该功能的最佳方式是什么?我们可以把它作为类或函数放在单独的文件中吗?如果是这样,我们怎么叫它呢?
发布于 2014-07-31 06:25:49
我的工作就是在一个单独的.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)https://stackoverflow.com/questions/24275579
复制相似问题