Mysql judges whether a database contains a certain table, and the pymysql tool function

View all tables in a database:

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

So to view a table in a library you can use:

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

In pymysql, you can write a simple utility function to query whether a table is contained in a database:

For the _query function here, please refer to the blog: The solution that python always times out when using 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 # 包含这个表

Guess you like

Origin blog.csdn.net/weixin_35757704/article/details/132694958