属性错误:__exit__ 在 python 3.4 上 [英] AttributeError:__exit__ on python 3.4

查看:39
本文介绍了属性错误:__exit__ 在 python 3.4 上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

原始代码:

import sys
import os
import latexmake

import mysql.connector
conn = mysql.connector.connect(user='root',password='oilwell',host='localhost',database='sqlpush1')

with conn:
    mycursor = conn.cursor()
mycursor=execute("SELECT DATE,oil,gas,oilprice,gasprice,totrev FROM results WHERE DATE BETWEEN '2011-01-01' AND '2027-12-01'")
rows = mycursor.fetchall()
a.write("\\documentclass{standalone}\\usepackage{booktabs}\n\n\\usepackage{siunitx}\r \n\
\r\n\\begin{document}\r\n\\begin{tabular}{ccS[table-format = 5.2]} \\\\ \\toprule\r")
a.write("Date & Oil & Gas & Oil price & Gas price & Total Revenue \\\\ \\midrule \r")
for row in rows:
    a = open("testtest.tex", "w")
    a.write("" + str(row[0]) + " & " + str(row[1]) + " & " + str(row[2]) + " & " + str(row[3]) + " & " + str(row[4]) + " & " + str(row[5]) + " \\\\ \r")

    a.write("\\bottomrule \\end{tabular}\r\\end{document}")
    a.close
print (os.path.getsize("testtest.tex"))
os.system('latexmk.py -q testtest.tex')
mycursor.close()
conn.close()
a.close()

IDLE 运行后,弹出红色错误提示

After run by IDLE, and red error pop up like

Traceback (most recent call last):
  File "C:\Users\Cheng XXXX\Desktop\tabletest.py", line 8, in <module>
    with conn:
AttributeError: __exit__

我检查了文件,无法提交错误,需要帮助.

I checked the file and cannot file mistake, need help.

推荐答案

您正在尝试将连接用作上下文管理器:

You are trying to use the connection as a context manager:

with conn:

这个对象没有实现像那样使用的必要方法;它不是上下文管理器,因为它(至少)缺少 <代码>__exit__ 方法.

This object doesn't implement the necessary methods to be used like that; it is not a context manager, as it is missing (at least) the __exit__ method.

如果您正在阅读使用不同 MySQL 库的教程或文档,请注意某些 库可能支持此功能,而不是这个库.例如,MySQLdb 项目 确实支持它.

If you are reading a tutorial or documentation that uses a different MySQL library, be aware that this feature may be supported by some libraries, just not this one. The MySQLdb project does support it, for example.

对于您的特定情况,您甚至根本不需要使用 with conn: 行;您没有对数据库进行任何更改,任何地方都不需要提交.您可以安全地删除 with conn: 行(将其下的所有内容取消缩进一步).否则,您可以在其他地方使用手动 conn.commit() 替换上下文管理器.

For your specific case, you don't even need to use the with conn: line at all; you are not making any changes to the database, no commit is required anywhere. You can safely remove the with conn: line (unindent everything under it one step). Otherwise you can replace the context manager with a manual conn.commit() elsewhere.

或者,您可以为此用例创建自己的上下文管理器,使用 @contextlib.contextmanager() 装饰器:

Alternatively, you can create your own context manager for this use-case, using the @contextlib.contextmanager() decorator:

from contextlib import contextmanager

@contextmanager
def manage_transaction(conn, *args, **kw):
    exc = False
    try:
        try:
            conn.start_transaction(*args, **kw)
            yield conn.cursor()
        except:
            exc = True
            conn.rollback()
    finally:
        if not exc:
            conn.commit()

并将其用作:

with manage_transaction(conn) as cursor:
    # do things, including creating extra cursors

您可以在其中为 connection.start_transaction() 调用.

where you can pass in extra arguments for the connection.start_transaction() call.

这篇关于属性错误:__exit__ 在 python 3.4 上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆