python 使用sqlalchemy 操作数据库

1.安装

pip install 
sqlalchemy

2.代码如下

  1. #!/usr/bin/python
  2. # coding=utf8
  3. from sqlalchemy import create_engine
  4. from sqlalchemy.ext.declarative import declarative_base
  5. from sqlalchemy.orm import sessionmaker
  6. from sqlalchemy import Column, Integer, String, DateTime, Boolean
  7. engine = create_engine(“mysql://root:root@127.0.0.1:3306/test?charset=utf8”)
  8. Session = sessionmaker(bind=engine)
  9. Base = declarative_base()
  10. class News(Base):
  11.     ‘ 新闻类型 ‘
  12.     __tablename__ = ‘news’
  13.     id = Column(Integer, primary_key=True)
  14.     title = Column(String(200), nullable=False)
  15.     content = Column(String(2000), nullable=False)
  16.     types = Column(String(10), nullable=False)
  17.     image = Column(String(300))
  18.     author = Column(String(20))
  19.     view_count = Column(Integer)
  20.     created_at = Column(DateTime)
  21.     is_valid = Column(Boolean)
  22. class MysqlOrmTest(object):
  23.     def __init__(self):
  24.         self.session = Session()
  25.     def add_one(self):
  26.         new_obj = News(
  27.             title=‘orm title’,
  28.             content=‘content’,
  29.             types=‘百家’
  30.         )
  31.         self.session.add(new_obj)
  32.         self.session.commit()
  33.         return new_obj
  34.     def get_one(self):
  35.         ‘ 获取一条数据 ‘
  36.         return self.session.query(News).get(1)
  37.     def get_more(self):
  38.         ‘ 获取多条数据 ‘
  39.         return self.session.query(News).filter_by(is_valid=1)
  40.     def update_data(self):
  41.         ‘ 修改数据 ‘
  42.         obj = self.session.query(News).get(38)
  43.         obj.is_valid = 0
  44.         self.session.add(obj)
  45.         self.session.commit()
  46.         return obj
  47.     def delete_data(self):
  48.         ‘ 删除数据 ‘
  49.         # 获取要删除的数据
  50.         data = self.session.query(News).get(39)
  51.         self.session.delete(data)
  52.         self.session.commit()
  53. def main():
  54.     obj = MysqlOrmTest()
  55.     # rest = obj.add_one()
  56.     # print(dir(rest))
  57.     # print(obj.get_one().title)
  58.     # print(obj.get_more().count())
  59.     # for row in obj.get_more():
  60.     # print(row.title)
  61.     # print(obj.update_data())
  62.     obj.delete_data()
  63. if __name__ == ‘__main__’:
  64.     main()

    原文作者:天下无敌庞成勇
    原文地址: http://blog.itpub.net/30523439/viewspace-2156931/
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞