以ORM方式操作SQL数据库(SQLite, MySQL, …) https://docs.sqlalchemy.org

基本用法

  1. #!/usr/bin/env python
  2. #-*- encoding: utf8 -*-
  3. from sqlalchemy import Column, Integer, String, create_engine, PrimaryKeyConstraint, Float
  4. from sqlalchemy.orm import sessionmaker
  5. from sqlalchemy.ext.declarative import declarative_base
  6. # 创建基类
  7. Base = declarative_base()
  8. # 自定义表类
  9. class NovoWES(Base):
  10. __tablename__ = 'novo_wes'
  11. chrom = Column(String(5))
  12. start = Column(Integer)
  13. end = Column(Integer)
  14. ref = Column(String(50))
  15. alt = Column(String(50))
  16. freq = Column(Float)
  17. __table_args__ = (
  18. PrimaryKeyConstraint('chrom', 'start', 'end', 'ref', 'alt'),
  19. )
  20. def __str__(self):
  21. return '<NovoWES(chrom={chrom}, start={start}, end={end}, ref={ref}, alt={alt}, freq={freq})>'.format(**self.__dict__)
  22. __repr__ = __str__
  23. # 连接数据库
  24. dbpath = 'test.db'
  25. engine = create_engine('sqlite:///' + dbpath, echo=True)
  26. # 自动创建表
  27. Base.metadata.create_all(engine)
  28. # 创建会话
  29. Session = sessionmaker(bind=engine)
  30. session = Session()
  31. # 插入数据
  32. context = {
  33. 'chrom': '1',
  34. 'start': 123456,
  35. 'end': 123456,
  36. 'ref': 'A',
  37. 'alt': 'T',
  38. 'freq': 0.001
  39. }
  40. session.add(NovoWES(**context))
  41. # 查询
  42. print session.query(NovoWES).filter_by(chrom='1', start=12345).first()
  43. print session.query(NovoWES.chrom)
  44. session.commit()
  45. session.close()