to_sql 方法不能設(shè)置主鍵册赛,這里記錄一種笨方法:
to_sql 方法執(zhí)行后執(zhí)行 sql 語句設(shè)置主鍵
from sqlalchemy import create_engine
engine = create_engine('mysql+cymysql://root:password@192.168.0.111:3306/pop')
with engine.connect() as con:
con.execute('ALTER TABLE `{}` ADD PRIMARY KEY (`id`);'.format(tablename))
# tablename 即數(shù)據(jù)庫表名
上面指令設(shè)置的主鍵沒有設(shè)置自動(dòng)遞增钠导,若要設(shè)置自動(dòng)遞增,執(zhí)行下面指令
with engine.connect() as con:
con.execute('alter table `{}` change id id int not null auto_increment;'.format(tablename))
# tablename 即數(shù)據(jù)庫表名