Search code examples
sqlalchemymysql-connector-python

AttributeError: 'Connection' object has no attribute 'is_connected'


I am working on a short project that deals with simple MySQL-python functions and came with an error. Using sqlalchemy, I have tried connecting MySQL and python but an error keeps popping up.

Traceback (most recent call last):

  line 198, in <module>
    menu()

  line 29, in menu
    create_database()

  line 55, in create_database
    if con.is_connected():

AttributeError: 'Connection' object has no attribute 'is_connected'

Here is my code:

from sqlalchemy import create_engine

import sys
def menu():
    loop='y'
    while(loop=='y' or loop=='Y'):
        print("........MENU.......")
        print("1. CREATE DATABASE")
        print("2. SHOW DATABASES")
        print("3. CREATE TABLE")
        print("4. SHOW TABLES")
        print("5. INSERT RECORD")
        print("6. UPDATE RECORD")
        print("7. DELETE RECORD")
        print("8. SEARCH RECORD")
        print("9. DISPLAY RECORD")
        print()
        print()
        choice=int(input("Enter the choice (1-9) : "))
        if(choice==1):
            create_database()
        elif(choice==2):
            show_databases()
        elif(choice==3):
            create_table()
        elif(choice==4):
            show_tables()
        elif(choice==5):
            insert_record()
        elif(choice==6):
            update_record()
        elif(choice==7):
            delete_record()
        elif(choice==8):
            search_record()
        elif(choice==9):
            display_record()
        else:
            print("Wrong Choice.")
        loop=input("Do you want more try? Press 'y' to continue...")
    else:
        sys.exit()
        
def create_database():
    engine = create_engine("mysql+mysqlconnector://root:****@localhost/employee")
    con = engine.connect()
    if con.is_connected():
        print("Successfully Connected")
    cur=con.cursor()
    cur.execute('create database if not exists employee')
    print()
    print("Database Created")
    con.close()

I have not shown the entire code because all of the choices come up with the same error. Please help me resolve this.


Solution

  • As mentioned in the comment to the question, engine.connect() returns a SQLAlchemy Connection object which does not have an is_connected() method.

    If you want to access the is_connected() method of the MySQL Connector/Python connection object then you'll need to get a raw DBAPI connection by calling raw_connection()

    dbapi_conn = engine.raw_connection()
    print(dbapi_conn.is_connected())
    

    … but I'm not sure how useful that would be because SQLAlchemy normally manages the DBAPI connections for us via its connection pool.