SqlAlchemy是Python編程語言下的一款ORM框架,該框架創建在數據庫API之上,使用關係對象映射進行數據庫操做,簡而言之:將對象轉換成SQL,而後使用數據API執行SQL並獲取執行結果。html
MySQL-Python : mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname> pymysql : mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>] MySQL-Connector : mysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname> cx_Oracle : oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...] 更多內容:http://docs.sqlalchemy.org/en/latest/dialects/index.html 備註: * Python2.7版本使用mysqldb * Python3.5版本使用pymysql * 使用pip或者源碼包安裝,確保環境能夠正常使用。 * 確保遠程數據庫服務器能夠正常使用,而且擁有遠程登錄權限 數據庫受權: * mysql -uroot -p # 登錄數據庫 * create database wang # 建立數據庫 * grant all on wang.* to wang@"%" identified by '123' # 受權數據庫 * flush privileges # 更新
#!/usr/bin/env python3 #coding:utf8 from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, ForeignKey # 建立數據庫鏈接 engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/wang", max_overflow=5) # 獲取元數據 metadata = MetaData() # 定義表 user = Table('user', metadata, Column('id', Integer, primary_key=True), Column('name', String(20)), ) color = Table('color', metadata, Column('id', Integer, primary_key=True), Column('name', String(20)), ) # 建立數據表,若是數據表存在,則忽視 metadata.create_all(engine)
#!/usr/bin/env python # -*- coding:utf-8 -*- from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine # 建立數據庫 engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/wang", max_overflow=5) # 生成一個SqlORM 基類 Base = declarative_base() # 定義表結構 class User(Base): # 表名 __tablename__ = 'users' # 定義id,主鍵惟一, id = Column(Integer, primary_key=True) name = Column(String(50)) # 尋找Base的全部子類,按照子類的結構在數據庫中生成對應的數據表信息 Base.metadata.create_all(engine) # 建立與數據庫的會話session class ,注意,這裏返回給session的是個class,不是實例 Session = sessionmaker(bind=engine) session = Session() # 獲取session,而後把對象添加到session # 最後提交併關閉。Session對象可視爲當前數據庫鏈接。
(2)增長python
#!/usr/bin/env python # -*- coding:utf-8 -*- from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/wang", max_overflow=5) Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String(50)) Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() #### 添加 ######## # 定義一個字段 zengjia = User(id=2, name='sbliuyao') # 添加字段 session.add(zengjia) # 添加多個字段 session.add_all([ User(id=3, name='sbyao'), User(id=4, name='liuyao') ]) # 提交以上操做,如今只是在內存中增長,回寫到數據庫,就必須作提交操做 session.commit()
(3)刪除mysql
#!/usr/bin/env python # -*- coding:utf-8 -*- from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/wang", max_overflow=5) Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String(50)) Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() ########### 刪除 ########## # 刪除user表,id大於2的字段 session.query(User).filter(User.id > 2).delete() session.commit()
(4)修改sql
#!/usr/bin/env python # -*- coding:utf-8 -*- from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/wang", max_overflow=5) Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String(50)) Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() # user表裏的id等於2的字段修改成id=6 session.query(User).filter(User.id == 2).update({'id' : 6}) session.commit()
(5)查詢數據庫
### 查詢方式1 #### # 查詢User表中字段是name=liuyao的第一條數據 ret = session.query(User).filter_by(name='liuyao').all() print(ret) # 輸出ret,這是個對象的內存地址 for i in ret: print(i.id,i.name) # 輸出ret的內容 ### 查詢方式2 #### # 查詢user表裏字段是name=liuyao的第一條數據 ret = session.query(User).filter_by(name='liuyao').first() print(ret) # 輸出的結果爲對象的內存地址 print(ret.name) # 輸出結果的name字段 print(ret.id) # 輸出結果的id字段 ### 查詢方式3 ### # 查詢user表裏字段是name是liuyao或者mayun的信息打印出來 ret = session.query(User).filter(User.name.in_(['liuyao','mayun'])).all() print(ret) for i in ret: print(i.name,i.id) ### 查詢方式4 ### # 能夠給返回的結果起一個別名,或者叫標籤:無關緊要 ret = session.query(User.name.label('')).all() # 這裏的關鍵是label方法,它的意思是把User的name字段改個名字叫name_label, # 其至關於執行了:select users.name as name_label from User print(ret,type(ret)) ### 查詢方式5 ### # 查詢User表根據id排序 ret = session.query(User).order_by(User.id).all() print(ret) for i in ret: print(i.name) ### 查詢方式6 ### # 查詢user表裏根據id排序輸入0到3的字段 ret = session.query(User).order_by(User.id)[0:3] print(ret) for i in ret: print(i.name) ### 查詢方式7 ### # 建立Query查詢,filter是where條件,最後調用one()返回惟一行,若是調用all()則返回全部行 user = session.query(User).filter(User.id=='5').one() print(type(user)) # 查看user的類型 print(user.name) # 查看對象的name屬性
(6)外鍵關聯編程
#!/usr/bin/env python3 #coding:utf8 # 導入所需模塊 from sqlalchemy import create_engine,func from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String,ForeignKey from sqlalchemy.orm import sessionmaker,relationship # 生成sqlorm基類 Base = declarative_base() # 建立數據庫鏈接 engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/wang", max_overflow=5) # 目的是一我的能夠擁有多本書,那麼在數據庫裏的一對多關係 class User(Base): # 表名 __tablename__ = 'user' # id字段 id = Column(String(20), primary_key=True) # 名字字段 name = Column(String(20)) # 一對多: # 內容不是表名而是定義的表結構名字 books = relationship('Book') class Book(Base): # 代表 __tablename__ = 'book' # id字段 id = Column(String(20), primary_key=True) # 名字字段 name = Column(String(20)) # 「多」的一方的book表是經過外鍵關聯到user表的: # ForeignKey是外鍵 關聯user表的id字段 user_id = Column(String(20), ForeignKey('user.id')) # 建立所需表 Base.metadata.create_all(engine) if __name__ == '__main__': # 綁定,生成會話 SessionCls = sessionmaker(bind=engine) session = SessionCls() # 建立用戶 liuyao = User(id='1',name='liuyao') ali = User(id='2',name='ali') # 添加字段 session.add_all([liuyao,ali]) # 提交 session.commit() # 建立白鹿原這本書,指定誰是擁有者 Whitedeer = Book(id='1',name='White_deer',user_id = '1') # 建立三體這本書,指定誰是擁有者 Threebody = Book(id='2',name='Three_body',user_id = '2') # 添加字段 session.add_all([Whitedeer,Threebody]) # 提交 session.commit()
#!/usr/bin/env python3 #coding:utf8 from sqlalchemy import Column, Sequence, String, Integer, ForeignKey from sqlalchemy import create_engine # 導入建立鏈接驅動 from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import relationship, backref # 這個url能夠用urlparse解析, 其中echo=True表示執行時顯示sql語句 engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/wang", max_overflow=5) # 生成了declarative基類, 之後的model繼承此類 Base = declarative_base() class Parent(Base): __tablename__ = 'parent' id = Column(Integer, primary_key=True) name = Column(String(64),unique=True,nullable=False) children = relationship("Child", back_populates="parent") class Child(Base): __tablename__ = 'child' id = Column(Integer, primary_key=True) name = Column(String(64),unique=True,nullable=False) parent_id = Column(Integer, ForeignKey('parent.id')) parent = relationship("Parent", back_populates="children") Base.metadata.create_all(engine) # 建立全部表結構 if __name__ == '__main__': SessionCls = sessionmaker(bind=engine) # 建立與數據庫的會話session class ,注意,這裏返回給session的是個class,不是實例 session = SessionCls() mama = Parent(id='1',name='mamaxx') baba = Parent(id='2',name='babaoo') session.add_all([mama,baba]) onesb = Child(id='1',name='onesb',parent_id='2') twosb = Child(id='2',name='twosb',parent_id='2') session.add_all([onesb,twosb]) session.commit()
#!/usr/bin/env python3 #coding:utf8 from sqlalchemy import create_engine,func,Table from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String,ForeignKey from sqlalchemy.orm import sessionmaker,relationship Base = declarative_base() # 關係表 Host2Group = Table('host_2_group',Base.metadata, Column('host_id',ForeignKey('hosts.id'),primary_key=True), Column('group_id',ForeignKey('group.id'),primary_key=True), ) engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/wang", max_overflow=5) class Host(Base): __tablename__ = 'hosts' id = Column(Integer,primary_key=True,autoincrement=True) hostname = Column(String(64),unique=True,nullable=False) ip_addr = Column(String(128),unique=True,nullable=False) port = Column(Integer,default=22) groups = relationship('Group', secondary= Host2Group, backref = 'host_list') class Group(Base): __tablename__ = 'group' id = Column(Integer,primary_key=True) name = Column(String(64),unique=True,nullable=False) Base.metadata.create_all(engine) # 建立全部表結構 if __name__ == '__main__': SessionCls = sessionmaker(bind=engine) session = SessionCls() g1 = Group(name='g1') g2 = Group(name='g2') g3 = Group(name='g3') g4 = Group(name='g4') session.add_all([g1,g2,g3,g4]) session.commit()