简体   繁体   English

Python数据库sqlite3

[英]Python database sqlite3

I got a little program with my code below: 我的代码如下:

def get_code(hex_pattern, database='./AndroidLockScreenRainbow.sqlite'):
    try:
        if os.path.exists(database):
            with lite.connect(database) as db:
                with db.cursor() as c:
                    c.execute("SELECT * FROM RainbowTable")
                    rows = c.fetchall()
                    for row in rows:
                        if row[0] == hex_pattern:
                            return row[1]
        else:
            raise lite.OperationalError("Database file not exists")
    except lite.OperationalError:
        print('Given SQL table not found!')

When the code reach the line with db.cursor() as c:, the program gives the following error 当代码到达以db.cursor()作为c:的行时,程序给出以下错误

 with db.cursor() as c: AttributeError: __exit__ 

What do I wrong? 我怎么了

The expression passed to the with statement ( db.cursor() ) in this case should return a context manager object. 在这种情况下,传递给with语句( db.cursor() )的表达式应返回上下文管理器对象。 A context manager object must have both an __enter__ and __exit__ method ( Under the hood, the with statement uses these the methods to ensure that the object is cleaned up correctly). 上下文管理器对象必须同时具有__enter____exit__方法(在__exit__with语句使用这些方法来确保正确清理对象)。

The sqlite3 cursor object doesn't implement these methods so it isn't a valid context manager method, hence the error message you're getting. sqlite3游标对象未实现这些方法,因此它不是有效的上下文管理器方法,因此会收到错误消息。

You could write your own context manager around cursor. 您可以围绕光标编写自己的上下文管理器。 You could write one yourself, but in most cases this isn't necessary, just assign db.cursor() to db directly 您可以自己写一个,但是在大多数情况下这不是必需的,只需直接将db.cursor()分配给db

c = db.cursor()

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

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