Mysql判断某个数据库中是否包含某个表,与pymysql工具函数

查看某个数据库中的全部表:

SELECT table_name
FROM information_schema.tables
WHERE table_schema = '数据库名'

因此查看某个库中的某个表可以使用:

SELECT table_name
FROM information_schema.tables
WHERE table_schema = '数据库名'
AND table_name = '表名称';

在pymysql中,可以写一个简单的工具函数,用于查询某个数据库中是否包含某个表:

这里的_query函数请参考博客:python使用pymysql总是超时的解决方案

from utils.sql_utils import _query


def sql_exists(database, table_name):
    sql_info = _query(f"""
        SELECT table_name
        FROM information_schema.tables
        WHERE table_schema = '{
      
      database}'
        AND table_name = '{
      
      table_name}';
    """, fetchone=True)
    if sql_info is None:
        return False # 不包含这个表
    else:
        return True # 包含这个表

猜你喜欢

转载自blog.csdn.net/weixin_35757704/article/details/132694958