# 连接数据库
connection = pymysql.connect(
host=host,
user=username,
password=password,
charset='utf8',
db=db_name)
1. 判断数据库中表格是否存在
def table_exists( table_name):
"""判断表是否存在"""
cs = connection.cursor() # 游标
sql = "show tables;"
cs.execute(sql)
tables = [cs.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
2.新建表格
create_table_sql = """
CREATE TABLE test_table(
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) UNIQUE ,
nickname VARCHAR(255) NOT NULL ,
birthday DATE ) """
('--------------新建表--------------')
cursor = connection.cursor()
cursor.execute(create_table_sql)
connection.commit()