python判断mysql中某张表是否存在

当向数据库添加表是,我们可能需要首先判断该表是否已经存在了,在继续后面的工作。

import pymysql
import re

def table_exists(con,table_name):        #这个函数用来判断表是否存在
    sql = "show tables;"
    con.execute(sql)
    tables = [con.fetchall()]
    table_list = re.findall('(\'.*?\')',str(tables))
    table_list = [re.sub("'",'',each) for each in table_list]
    if table_name in table_list:
        return 1        #存在返回1
    else:
        return 0        #不存在返回0

connect = pymysql.connect(
        user = 'root',
        password = 'password',
        db = 'MYSQL',
        host = '127.0.0.1',
        port = 3306,
        charset = 'utf8'
        )
con = connect.cursor()

table_name = 'animal'
if(table_exists(con,table_name) != 1):
    print("表不存在,可以添加一张")


参考地址:https://zhidao.baidu.com/question/394979567818963085.html



猜你喜欢

转载自blog.csdn.net/qq_36523839/article/details/80639297