首页 > 代码库 > day13 SQLAlchemy

day13 SQLAlchemy

ORM:也叫关系对象映射

本篇要点:

  • 原生模块 pymsql
  • ORM框架 SQLAchemy

pymysql

pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同。

需要准备的环境:

  • MySQL(服务端)
  • pymysql(操作客户端)
    • pymysql安装参考:http://www.cnblogs.com/woider/p/5926744.html

pymysql的使用操作:

  • 执行SQL语句:

 

 

SQLAchemy

 

技术分享

SQLAlchemy本身无法操作数据库,其必须以来pymsql等第三方插件,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
  • 创建表:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
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+pymysql://root:123456@10.70.18.100:3306/ttt",max_overflow=5)    #连接数据库
Base = declarative_base()
#创建单表:
class Users(Base):     #类必须要继承Base
    __tablename__ = users     #表名
    id = Column(Integer,primary_key=True)    #创建列
    name = Column(String(32))
    extra = Column(String(16))
    __table_args__ = (
        UniqueConstraint(id,name,name=centos),     #联合索引
        Index(ix_id_name,name,extra),
    )

#一对多
class Favor(Base):
    __tablename__ = favor
    nid = Column(Integer,primary_key=True)
    caption = Column(String(50),default=red,unique=True)
class Person(Base):
    __tablename__ = person
    nid = Column(Integer,primary_key=True)
    name = Column(String(32),index=True,nullable=True)
    favor_id = Column(Integer,ForeignKey("favor.nid"))     #根上一个favor的nid做外键
#多对多
class ServerToGroup(Base):
    __tablename__ = servertogroup
    id = Column(Integer,primary_key=True,autoincrement=True)
    hostname = Column(String(64),unique=True,nullable=False)

class Group(Base):
    __tablename__ = group
    id = Column(Integer,primary_key=True)
    name = Column(String(64),unique=True,nullable=False)

class Server(Base):
    __tablename__ = server
    id = Column(Integer,primary_key=True,autoincrement=True)
    hostname = Column(String(64),unique=True,nullable=False)
    port = Column(Integer,default=22)

# def init_db():
#     Base.metadata.create_all(engine)
# init_db()    #创建

def drop_db():
    Base.metadata.drop_all(engine)

drop_db()    #删除

day13 SQLAlchemy