【问题标题】:How to simplify MySQLdb connect from being called many times如何简化 MySQLdb 连接被多次调用
【发布时间】:2014-06-18 01:04:39
【问题描述】:

我有以下 MySQL 连接:

import MySQLdb as mdb
rbpdb = mdb.connect(host='db01.myhost.co.nl,
                        user='pdbois',
                        passwd='triplex',
                        db='myxxx')

在编码过程中,我会在很多功能中多次重复使用这个连接。 用于读取、创建和更新数据库。

在不必多次调用上述 sn-ps 的情况下实现该功能的最佳方法是什么? 我们可以将它作为类或函数放在单独的文件中吗?如果是,我们怎么称呼它?

【问题讨论】:

标签: python mysql reusability


【解决方案1】:

对我有用的只是一个单独的 .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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-27
    • 2017-06-06
    • 2014-05-25
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多