代码如下
from sqlalchemy import create_engine
def table_exists(engine, table_name): # 这个函数用来判断表是否存在
with engine.connect() as con:
sql = "show tables;"
tables = con.execute(sql).fetchall() # 读取show tables;执行后的全部表名
for table_col in tables:
if table_name == table_col[0]:
return True
return False
if __name__ == '__main__':
# engine = create_engine("mysql+pymysql://用户名:密码@127.0.0.1:3306/数据库名")
engine = create_engine('mysql+pymysql://testuser:testpassword@localhost:3306/{}'.format("test_db"), encoding='utf8')
if table_exists(engine, "test_csv"):
print('存在')
else:
print('不存在')