目錄html
SqlAlchemypython
外鍵mysql
SqlAlechemysql
SQLAlchemy是Python編程語言下的一款ORM框架,該框架創建在數據庫API之上,使用關係對象映射進行數據庫操做,簡言之即是:將對象轉換成SQL,而後使用數據API執行SQL並獲取執行結果。數據庫
Dialect用於和數據API進行交流,根據配置文件的不一樣調用不一樣的數據庫API,從而實現對數據庫的操做,如:編程
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
建立表(實例方法)ubuntu
from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, ForeignKey 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)), ) #表結構 engine = create_engine("mysql+pymysql://root:1234@127.0.0.1:3306/mydb?charset=utf8", max_overflow=5)#連接數據庫 metadata.create_all(engine)
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, ForeignKey 5 6 metadata = MetaData() 7 8 user = Table('user', metadata, 9 Column('id', Integer, primary_key=True), 10 Column('name', String(20)), 11 ) 12 13 color = Table('color', metadata, 14 Column('id', Integer, primary_key=True), 15 Column('name', String(20)), 16 ) 17 engine = create_engine("mysql+mysqldb://root:123@127.0.0.1:3306/s11", max_overflow=5) 18 19 conn = engine.connect() 20 21 # 建立SQL語句,INSERT INTO "user" (id, name) VALUES (:id, :name) 22 conn.execute(user.insert(),{'id':7,'name':'seven'}) 23 conn.close() 24 25 # sql = user.insert().values(id=123, name='wu') 26 # conn.execute(sql) 27 # conn.close() 28 29 # sql = user.delete().where(user.c.id > 1) 30 31 # sql = user.update().values(fullname=user.c.name) 32 # sql = user.update().where(user.c.name == 'jack').values(name='ed') 33 34 # sql = select([user, ]) 35 # sql = select([user.c.id, ]) 36 # sql = select([user.c.name, color.c.name]).where(user.c.id==color.c.id) 37 # sql = select([user.c.name]).order_by(user.c.name) 38 # sql = select([user]).group_by(user.c.name) 39 40 # result = conn.execute(sql) 41 # print result.fetchall() 42 # conn.close()
建立表(類方法)session
#!/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,and_,or_ Base = declarative_base() #生成一個SqlORM的基類 engine = create_engine("mysql+mysqldb://root:123@127.0.0.1:3306/s12",echo=True) 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) Base.metadata.create_all(engine) #建立全部表結構 if __name__ == '__main__': SessionCls = sessionmaker(bind=engine) #建立與數據庫的會話 session = SessionCls() #連接的實例 # add(添加數據) # h2 = Host(hostname='localhost',ip_addr='127.0.0.1') # h3 = Host(hostname='ubuntu5',ip_addr='192.168.1.24',port=20000) # session.add(h2) # session.add(h3) # session.add_all([h2,h3]) # update(修改數據) # obj = session.query(Host).filter(Host.hostname=='localhost').first()#查詢數據 # print("++>",obj) # obj.hostname = "test server" # delete(刪除數據) # obj = session.query(Host).filter(Host.hostname=='test server').first() # session.delete(obj) # session.commit()
1 # ########## 增 ########## 2 # u = User(id=2, name='sb') 3 # session.add(u) 4 # session.add_all([ 5 # User(id=3, name='sb'), 6 # User(id=4, name='sb') 7 # ]) 8 # session.commit() 9 10 # ########## 刪除 ########## 11 # session.query(User).filter(User.id > 2).delete() 12 # session.commit() 13 14 # ########## 修改 ########## 15 # session.query(User).filter(User.id > 2).update({'cluster_id' : 0}) 16 # session.commit() 17 # ########## 查 ########## 18 # ret = session.query(User).filter_by(name='sb').first() 19 20 # ret = session.query(User).filter_by(name='sb').all() 21 # print ret 22 23 # ret = session.query(User).filter(User.name.in_(['sb','bb'])).all() 24 # print ret 25 26 # ret = session.query(User.name.label('name_label')).all() 27 # print ret,type(ret) 28 29 # ret = session.query(User).order_by(User.id).all() 30 # print ret 31 32 # ret = session.query(User).order_by(User.id)[1:3] 33 # print ret 34 # session.commit()
外鍵——一對多oracle