打开和关闭mysql连接

时间:2014-09-09 13:42:34

标签: python mysql

我有这个python函数:

import MySQLdb as mdb
def sql_query(sql):
    try:
        con = mdb.connect('localhost', 'user', '', 'dbs')
        with con:
            cur = con.cursor()
            cur.execute(sql)
            results = cur.fetchall()
            return results
    except mdb.Error, e:
        sys.exit(1)
    finally:
        if con:
            con.close()

然后我有大量的代码调用这个函数,有时con关闭,我得到这个回溯:

Traceback (most recent call last):
  File "users.py", line 431, in <module>
    orders = get_orders(user_id, mongo_user_id, address_book_list)
  File "users.py", line 343, in get_orders
    order_lines =  get_order_lines(order_id)
  File "users.py", line 288, in get_order_lines
    for item in sql_query(get_order_lines_sql):
  File "users.py", line 57, in sql_query
    if con:
UnboundLocalError: local variable 'con' referenced before assignment

我的get_orders代码就像:

def get_orders(user_id, mongo_user_id, address_book_list):
    # we just want orders that are less than 2 years old
    get_orders_sql = """SELECT order_id, state, state2, stamp, reference, comments, address_id, delivery_id, user_id FROM user_orders WHERE address_id IS NOT NULL and stamp >= '2012-01-01 00:00:00' and user_id='%s' ORDER BY stamp DESC"""% (user_id)
    # delivery_id - this is the shipping option the user chose.
    for items in sql_query(get_orders_sql):
        #print items
        order_id = items[0]

订单中约有50K行

任何建议非常感谢

1 个答案:

答案 0 :(得分:0)

您需要初始化con,因为假设mdb.connect出现错误时出现错误,当final con尚未初始化时<{1}}

import MySQLdb as mdb
def sql_query(sql):
    con='' #this should be intiated
    try:
        con = mdb.connect('localhost', 'user', '', 'dbs')
        with con:
            cur = con.cursor()
            cur.execute(sql)
            results = cur.fetchall()
            return results
    except mdb.Error, e:
        sys.exit(1)
    finally:
        if con:
            con.close()