简体   繁体   中英

create new mysql database and tables using sqlalchemy

I'd like to create new database and new tables to this database using sqlalchemy. and I have to write create_engine twice, is there any easier writing method to do these things? my code is here:

from sqlalchemy import create_engine
import pymysql

user = 'admin'
password = ''
host = 'database-1.czswegfdjhpn.us-east-1.rds.amazonaws.com'
port = 3306

engine = create_engine(url="mysql+pymysql://{0}:{1}@{2}:{3}".format(
            user, password, host, port))

conn = engine.connect()
print('connect successfull')

conn.execute("commit")
conn.execute('create database covid_19')

database = 'covid_19'

engine1 = create_engine(url="mysql+pymysql://{0}:{1}@{2}:{3}/{4}".format(
            user, password, host, port, database))

conn1 = engine.connect()
print('connect successfull')

df.to_sql(name="covid_19_world_cases_deaths_testing",con=engine1, if_exists='append', index=False, chunksize=200)

Haven't tested this, however could you simply call

conn.execute(“USE covid_19”)

to change the database of the existing connection?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM