连接数据库
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 ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;"""
# ENGINE=InnoDB 数据库引擎,默认为InnoDB
# AUTO_INCREMENT设置自增从1开始
# CHARSET 语言编码,防止表格数据出现乱码
cursor = connection.cursor()
cursor.execute(create_table_sql)
connection.commit()
----------------------------------------------------------------------------------------------------------------
Update:
当表格不存在时,直接创建(存在时,不创建):
table_name = 'students'
create_sql = """
CREATE TABLE IF NOT EXISTS %s(
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL,
age INT NOT NULL,
)""" % table_name
cursor = connection.cursor()
cursor.execute(create_sql)
connection.commit()
当表格存在时会出现警告:Warning: (1050, "Table 'students' already exists")