SQLAlchemy 使用
因为有用到 所以记录一下 呵呵
使用SQLAlchemy 这种ORM的方式操作数据库
关于ORM的介绍具体可以参见 http://en.wikipedia.org/wiki/Object-relational_mapping
SQLAlchemy 官网:http://www.sqlalchemy.org/
安装方式:从源码包安装或者 easy_install SQLAlchemy(不得不说 用包安装真是方便啊 不用自己去安装各种依赖包)
安装mysql ap i: apt-get install python-mysqldb
使用的一个demo
1 #!/usr/bin/env python 2 from sqlalchemy import * 3 from sqlalchemy import create_engine 4 from sqlalchemy.ext.declarative import declarative_base 5 from sqlalchemy import Column, Integer, String, ForeignKey 6 from sqlalchemy import distinct 7 from sqlalchemy.orm import sessionmaker 8 #engine = create_engine('mysql://root:nosql@localhost/serverlist', echo=False) 9 10 engine = create_engine('mysql://users:passwd@localhost/videoupload', connect_args={'charset':'utf8'},echo=False) 11 Base = declarative_base() 12 Session = sessionmaker(bind=engine) 13 session = Session() 14 15 class VideoUpload(Base): 16 __tablename__ = 'videoupload' 17 num = Column(Integer, primary_key=True) 18 vid = Column(String) 19 filepath = Column(String) 20 sourceip = Column(String) 21 state = Column(String) 22 snapshot = Column(String) 23 24 25 def __init__(self,vid='',filepath='',sourceip='',state='',snapshot=''): 26 self.vid = vid 27 self.filepath = filepath 28 self.sourceip = sourceip 29 self.state = state 30 self.snapshot = snapshot 31 32 33 class FailVideoUpload(Base): 34 __tablename__ = 'fail_videoupload' 35 num = Column(Integer, primary_key=True) 36 file_path = Column(String) 37 file_name = Column(String) 38 file_content_type = Column(String) 39 file_size = Column(String) 40 41 def __init__(self,file_path='',file_name='',file_content_type='',file_size=''): 42 self.file_path = file_path 43 self.file_name = file_name 44 self.file_content_type = file_content_type 45 self.file_size = file_size 46 47 48 49 if __name__ == '__main__': 50 #pVideoupload = VideoUpload() 51 #pVideoupload.insert().values(vid='123',sourceip='123',state='true',) 52 my_vp = VideoUpload('test', 'true', 'true','sdf') 53 my_fvp = FailVideoUpload('/home','123','jpg','123') 54 session.add(my_vp) 55 session.add(my_fvp) 56 session.commit()