pymysql判断表是否存在

import pymysql
import re

db = pymysql.connect(host='localhost',user='root',password='123456',db='spiders')
# db = pymysql.connect(host='localhost',user='root',password='123456')
cursor = db.cursor()
cursor.execute('SELECT VERSION()')
print('Database Version:',cursor.fetchone())

# 判断数据库是否存在
def data_exists(cursor,database):
    sql = "show databases"
    cursor.execute(sql)
    databases = [cursor.fetchall()]
    # print(type(databases))
    # print(databases)
    databases_list = re.findall('(\'.*?\')',str(databases))
    # print(databases_list)
    databases_list = [re.sub("'",'',each)for each in databases_list]
    # print(databases_list)
    if database in databases_list:
        print("database exists")
    else:
        # 创建数据库
        sql = "CREATE DATABASE IF NOT EXISTS " + database
        try:
            cursor.execute(sql)
            db.commit()
            print("Successfully added database")
        except:
            db.rollback()
            print("Successfully added database")

# 判断表是否存在
def table_exists (cursor,table,*createTable):
    sql = "show tables"
    cursor.execute(sql)
    tables = cursor.fetchall()
    # print(tables)
    tables_list = re.findall('(\'.*?\')',str(tables))
    # print(tables_list)
    tables_list = [re.sub("'",'',each)for each in tables_list]
    # print(tables_list)
    if table in tables_list:
        print("table exists")
    else:
        print("table not exists")
        try :
            sql = createTable[0]
            # print(sql)
            cursor.execute(sql)
            db.commit()
            print("Successfully added table")
        except:
            db.rollback()
            print("UnSuccessfully added table")

if __name__ == "__main__":
    # 表名
    table = "students1"
    # 创建表语句
    createTable = 'CREATE TABLE IF NOT EXISTS students1 (id VARCHAR(255) NOT NULL,name VARCHAR(255) NOT NULL,age INT NOT NULL,PRIMARY KEY(id))'
    table_exists(cursor,table,createTable)
    # cursor.execute(createtable)
    cursor.execute('show tables')
    print(cursor.fetchall())

你可能感兴趣的:(#,python数据储存)