python使用sqlalchemy判断数据库是否包含某张表
  TEZNKK3IfmPf 2023年11月14日 33 0

代码如下

from sqlalchemy import create_engine


def table_exists(engine, table_name):  # 这个函数用来判断表是否存在
    with engine.connect() as con:
        sql = "show tables;"
        tables = con.execute(sql).fetchall() # 读取show tables;执行后的全部表名
        for table_col in tables:
            if table_name == table_col[0]:
                return True
        return False


if __name__ == '__main__':
    # engine = create_engine("mysql+pymysql://用户名:密码@127.0.0.1:3306/数据库名")
    engine = create_engine('mysql+pymysql://testuser:testpassword@localhost:3306/{}'.format("test_db"), encoding='utf8')
    if table_exists(engine, "test_csv"):
        print('存在')
    else:
        print('不存在')
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   29天前   32   0   0 excelpython
TEZNKK3IfmPf