【问题标题】:AttributeError:__exit__ on python 3.4AttributeError:__exit__ on python 3.4
【发布时间】:2015-06-11 13:47:58
【问题描述】:

原代码:

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运行后,弹出红色错误

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

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

【问题讨论】:

  • conn 不是上下文管理器,它是 with 尝试存储 conn.__exit__ 以在上下文退出时调用。
  • @MartijnPieters 你能更具体一点吗?我该如何解决这个案子?非常感谢。
  • 不要将mysql.connector 连接用作上下文管理器。它可能适用于其他 MySQL 库,但不是这个。

标签: python mysql python-3.x with-statement mysql-connector-python


【解决方案1】:

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

with conn:

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

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

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

或者,您可以为此用例创建自己的上下文管理器,使用 @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() call 传递额外的参数。

【讨论】:

  • 我的python版本是3.4,MySQLdb不支持。那么,有没有办法用 MySQL Connector/Python 来执行这个脚本呢? python新手,非常感谢您的时间。
  • @ChengZhang:可以,只是不要使用那个功能。您可以使用我的替代方法,或删除 with conn: 行(取消缩进其余部分),并在末尾添加明确的 conn.commit()
  • @Martjin Pieters 你的意思是删除“with conn”并将“conn.commit()”放在最后?
  • @ChengZhang:是的。但是conn.commit() 甚至都不需要;你永远不会对提交进行任何更改
  • @Martjin Pieters 新的错误出来了,“NameError: name 'a' is not defined”,但是在“wiht conn”下,没有这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-16
  • 2015-01-19
  • 2016-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多