繁体   English   中英

如何简化MySQLdb连接以免被多次调用

[英]How to simplify MySQLdb connect from being called many times

我有以下MySQL连接:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM