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

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

我正在处理一个处理简单 MySQL-python 函数的简短项目,但出现错误。使用 sqlalchemy,我尝试连接 MySQL 和 python,但不断弹出错误。

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'

这是我的代码:

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()

我没有展示完整的代码,因为所有的选择都会出现同样的错误。请帮我解决这个问题。

如问题评论中所述,engine.connect() returns 一个没有 is_connected() 方法的 SQLAlchemy Connection 对象。

如果您想访问 MySQL Connector/Python 连接对象的 is_connected() method,那么您需要通过调用 raw_connection() 来获取原始 DBAPI 连接……

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

…但我不确定这会有多大用处,因为 SQLAlchemy 通常通过其连接池为我们管理 DBAPI 连接。