Advertisement
shinemic

sqlalchemy_test

Oct 27th, 2019
440
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.11 KB | None | 0 0
  1. from sqlalchemy import create_engine, MetaData, Table, Column, String
  2. from sqlalchemy.orm import sessionmaker
  3. from sqlalchemy.engine.url import URL
  4. import warnings
  5.  
  6.  
  7. mysql_url_params = {
  8.     'drivername': 'mysql+pymysql',
  9.     'username': '',
  10.     'password': '',
  11.     'host': '',
  12.     'port': 3306,
  13.     'database': ''
  14. }
  15.  
  16. engine = create_engine(URL(**mysql_url_params), encoding='utf-8')
  17. metadata = MetaData(engine, reflect=True)
  18.  
  19. blogrolls = Table(
  20.     'BlogRolls', metadata,
  21.     Column('blogger', String(40), primary_key=True),
  22.     Column('href', String(200), nullable=False)
  23. )
  24.  
  25. if 'blogrolls' in metadata.tables:
  26.     blogrolls.drop(engine)
  27. blogrolls.create(engine)
  28.  
  29. session = sessionmaker(bind=engine)()
  30.  
  31. with warnings.catch_warnings():
  32.     warnings.simplefilter("ignore")
  33.     insert_result = session.execute(blogrolls.insert().prefix_with('IGNORE'), [
  34.         {'blogger': 'Hortencia Pickrell', 'href': 'http://transportative.com/repeatedly/hydromys'},
  35.         {'blogger': 'Krystin Shellhamer', 'href': 'http://mare.com/periphyllum/uncrushed'},
  36.         {'blogger': 'Meghan Ballreich', 'href': 'https://gainst.com/trifle/pyrotherium'},
  37.         {'blogger': 'Adriana Piatkowski', 'href': 'https://seminally.com/undiatonic/peridotitic'},
  38.         {'blogger': 'Karrie Ritrovato', 'href': 'http://foreadvise.com/precant/flirtationless'},
  39.         {'blogger': 'Letitia Lukow', 'href': 'https://overidle.com/unidactyl/anemonal'},
  40.         {'blogger': 'Genoveva Kosmala', 'href': 'https://jutty.com/baryton/undertime'},
  41.         {'blogger': 'Dona Catala', 'href': 'http://plowbote.com/plasm/autoxidation'},
  42.         {'blogger': 'Christy Kriesel', 'href': 'http://apotactici.com/incinerable/teutonist'},
  43.         {'blogger': 'Erwin Hatteyer', 'href': 'http://hyperphoria.com/reachless/canary'},
  44.         {'blogger': 'Erwin Hatteyer', 'href': '-- Duplicate Record --'},
  45.         {'blogger': 'Rubbish', 'href': None},
  46.     ])
  47.     session.commit()
  48.  
  49. print('更新记录数:', insert_result.rowcount)
  50. for i, (blogger, href) in enumerate(engine.execute('SELECT * FROM blogrolls').fetchall(), 1):
  51.     print(f'{i:>2} | {blogger:18} | {href}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement