sqlalchemy是Python編程語言下的一款ORM框架,該框架創建在數據庫API之上,使用關係對象映射進行數據庫操做,簡言之即是:將對象轉換成SQL,而後使用數據API執行SQL並獲取執行結果。python
SQLAlchemy自己沒法操做數據庫,其必須以pymsql等第三方插件,Dialect用於和數據API進行交流,根據配置文件的不一樣調用不一樣的數據庫API,從而實現對數據庫的操做。mysql
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...]
使用 Engine/ConnectionPooling/Dialect 進行數據庫操做,Engine使用ConnectionPooling鏈接數據庫,而後再經過Dialect執行SQL語句。sql
#!/usr/bin/env python # -*- coding:utf-8 -*- from sqlalchemy import create_engine engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=5) # 執行SQL # cur = engine.execute( # "INSERT INTO hosts (host, color_id) VALUES ('1.1.1.22', 3)" # ) # 新插入行自增ID # cur.lastrowid # 執行SQL # cur = engine.execute( # "INSERT INTO hosts (host, color_id) VALUES(%s, %s)",[('1.1.1.22', 3),('1.1.1.221', 3),] # ) # 執行SQL # cur = engine.execute( # "INSERT INTO hosts (host, color_id) VALUES (%(host)s, %(color_id)s)", # host='1.1.1.99', color_id=3 # ) # 執行SQL # cur = engine.execute('select * from hosts') # 獲取第一行數據 # cur.fetchone() # 獲取第n行數據 # cur.fetchmany(3) # 獲取全部數據 # cur.fetchall()
ORM框架的做用就是把數據庫表的一行記錄與一個對象互相作自動轉換。 正確使用ORM的前提是瞭解關係數據庫的原理。 ORM就是把數據庫表的行與相應的對象創建關聯,互相轉換。 因爲關係數據庫的多個表還能夠用外鍵實現一對多、多對多等關聯,相應地, ORM框架也能夠提供兩個對象之間的一對多、多對多等功能。數據庫
create_engine方法參數('使用數據庫+數據庫連接模塊://數據庫用戶名:密碼@ip地址:端口/要鏈接的數據庫名稱?charset=utf8',echo=True表示是否查看生成的sql語句,max_overflow=5) max_overflow=5 表示最大鏈接數 declarative_base()建立一個SQLORM基類 Column()設置字段屬性 create_all()向數據庫建立指定表 建立表數據類型 整數型:TINYINT,SMALLINT,INT,BIGINT Boolean()對應TINYINT Integer()對應INT SMALLINT()對應SMALLINT BIGINT()對應BIGINT 浮點型:FLOAT,DOUBLE,DECIMAL(M,D) DECIMAL()對應DECIMAL Float()對應FLOAT REAL()對應DOUBLE 字符型:CHAR,VARCHAR String(40)對應VARCHAR CHAR()對應CHAR 日期型:DATETIME,DATE,TIMESTAMP DATETIME()對應DATETIME DATE()對應DATE TIMESTAMP()對應TIMESTAMP 備註型:TINYTEXT,TEXT, Text()對應TEXT UnicodeText(10)對應TINYTEXT ############################################################################## # -*- coding:utf-8 -*- import sqlalchemy from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index from sqlalchemy.orm import sessionmaker, relationship from sqlalchemy import create_engine engine = create_engine("mysql+mysqlconnector://root:123456@127.0.0.1:3306/project_db", echo=True) Base = declarative_base() class People(Base): __tablename__ = "people" # 表名 id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String(16), nullable=False) age = Column(Integer, nullable=False) job = Column(String(16), nullable=False) salary = Column(Integer, nullable=False) Base.metadata.create_all(engine) # 新建表 # Base.metadata.drop_all(engine) # 刪除表
primary_key=True主鍵索引
autoincrement=True自增字段
index=True給當前字段建立普通索引
unique=True給當前字段建立惟一索引
UniqueConstraint('字段','字段',name='索引名稱')建立惟一組合索引
Index('索引名稱','字段','字段')建立普通組合索引
default='abc'設置字段默認值,不怎麼可靠
ForeignKey("鏈接表名稱.鏈接表主鍵字段")設置外鍵鏈表
nullable=False類容不能爲空編程
# -*- coding:utf-8 -*- import sqlalchemy from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index from sqlalchemy.orm import sessionmaker, relationship from sqlalchemy import create_engine engine = create_engine("mysql+mysqlconnector://root:123456@127.0.0.1:3306/project_db", echo=True) Base = declarative_base() class People(Base): __tablename__ = "people" id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String(16), nullable=False) age = Column(Integer, nullable=False) job = Column(String(16), nullable=False) salary = Column(Integer, nullable=False) books = relationship('book') # 這裏的book爲小寫 class Book(Base): __tablename__ = "book" id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String(16), nullable=False) author = Column(String(16), nullable=False) people_id = Column(Integer, ForeignKey('people.id')) # 這裏的people爲小寫 Base.metadata.create_all(engine) # 新建表 #Base.metadata.drop_all(engine) # 刪除表
class Server(Base): __tablename__ = "server" id = Column(Integer, primary_key=True, autoincrement=True) hostname = Column(String(8)) class Group(Base): __tablename__ = "group" id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String(16), unique=True) class ServertoGroup(Base): __tablename__ = "servertogroup" id = Column(Integer, primary_key=True, autoincrement=True) server_id = Column(Integer, ForeignKey('server.id')) group_id = Column(Integer, ForeignKey('group.id'))