Code

#!/usr/bin/python import mysql.connector from mysql.connector import Error sql = """select now();""" try: connection = mysql.connector.connect(host='127.0.0.1', database='test', user='root', password='12345') if connection.is_connected() : print('Connected to MySQL database') except Error as e: print(e) with connection.cursor() as cursor: cursor.execute(sql) result = [row[0] for row in cursor] 

Displays "Connected to MySQL database" and fails with the error:

 Connected to MySQL database Traceback (most recent call last): File "./test.py", line 16, in <module> with connection.cursor() as cursor: AttributeError: __exit__ 

Why and how to make work with the operator with?

    1 answer 1

    Description of the reason
    with uses the __enter__ and __exit__ methods and in this case the object returned by cursor() no __exit__ method
    Those. with with this function will not work
    Use simple assignment.

     cursor = connection.cursor() cursor.execute(sql) result = [row[0] for row in cursor] 
    • The connection has an exit, but still does not work. Why? pastebin.com/0bj3VK9e - user211049
    • @ user211049, connection and cursor are missing the necessary methods Script to check - Maxim Timakov