sqlalchemy学习--重要参数
sqlalchemy学习--重要参数

Base = declarative_base
基类:
1.存储表
2.建立class-Table 的映射关系
engine = create_engine('mysql://root:root@localhost:3307/test', echo=False)
连接数据库
Session = sessionmaker(bind=engine)
sess = Session()
会话
1.保存上下文信息
2.容器,存储对对象的操作。

metadata
所有Base的子类,共享这个metadata
1.所有Table存储在此metadata中
2.共享此metadata的属性和方法。
mapper
将class -- Table 进行映射
Column 重要参数 1.name 字段名(可选,该参数优先级高于变量名) 2.type_ 字段类型,注意:MySQL中,String类型必须指定长度 3.primary_key 如该参数为True,那么该字段为主键(False) 4.unique 如该参数如果为True,相应字段具有唯一性(False) 5.index 如该参数为True,相应字段为索引字段(False) 6.nullable 如该参数为False,该字段不允为空(True) 7.ForeignKey 通过该参数指定外键 8.default 指定该字段的默认值
engine 特性及重要参数 1.Engine是数据库核心接口 2.Lazy Connecting,此时并未真正建立其和数据库的连接,直到:engine.execute(),engine.connect()等方法被调用才会真正建立连接 3.pool_size = 5; 连接池的大小,默认为 5 4.max_overflow = 10; 连接池可溢出最大数量 默认为10 [不放入连接池] 5.echo = False; 打印SQL语句,调用logging模块,默认为False 6.encoding = 'utf-8'; 编码方式,默认为 utf8 7.pool_recycle = -1 连接回收时间 -1,永不回收(推荐设置3600即1h) 注意: MySQL连接的默认断开时间是 8小时 8.pool_timeout=30 尝试从连接池中获取连接的超时时间
反向映射(即将数据库中的表映射成程序中的表对象)
Base.metadata.reflect(engine) print(Base.metadata.tables)
print(Student.__table__) # 查看类对应的表 print(Student.__mapper__) # 查看类对应的mapper函数
engine = create_engine("...") Session = sessionmaker(bind=engine) # new session. no connections are in use. session = Session() try: # first query. a Connection is acquired # from the Engine, and a Transaction # started. item1 = session.query(Item).get(1) # second query. the same Connection/Transaction # are used. item2 = session.query(Item).get(2) # pending changes are created. item1.foo = 'bar' item2.bar = 'foo' # commit. The pending changes above # are flushed via flush(), the Transaction # is committed, the Connection object closed # and discarded, the underlying DBAPI connection # returned to the connection pool. session.commit() except: # on rollback, the same closure of state # as that of commit proceeds. session.rollback() raise finally: # close the Session. This will expunge any remaining # objects as well as reset any existing SessionTransaction # state. Neither of these steps are usually essential. # However, if the commit() or rollback() itself experienced # an unanticipated internal failure (such as due to a mis-behaved # user-defined event handler), .close() will ensure that # invalid state is removed. session.close()
关于数据库 字段为时间戳问题的探究:
/*create_time 自动保存创建时间;modify_time 自动保存修改时间*/ create table teacher(id int not null auto_increment primary key, name varchar(30),create_time TIMESTAMP default CURRENT_TIMESTAMP not null,modify_time TIMESTAMP default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP not null)ENGINE=InnoDB DEFAULT CHARSET=utf8;
show create table students; # 查看创建数据表的命令
import datetime import time from sqlalchemy import create_engine, Column, Integer, String, TIMESTAMP, text from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker Base = declarative_base() engine = create_engine("mysql+pymysql://root:root@localhost/sqla?charset=utf8") class Student(Base): __tablename__ = "students" __table_args__ = { # "mysql_engine":"MyISAM", "mysql_charset":"utf8" } # show create table students 可以查看建表语句;默认是Innodb,lating-1.如果想显示中文需要修改指定建表的类型,同时,engine也要指定编码格式 id = Column(Integer,primary_key=True) name = Column(String(30)) # first update_time 必须在上面, update_time = Column(TIMESTAMP,nullable=False) create_time = Column(TIMESTAMP,nullable=False,server_default=text("current_timestamp")) # create_time = Column(TIMESTAMP(True),nullable=False,server_default=text("now()")) # create_time = Column(TIMESTAMP(True),default=datetime.datetime.now()) # show create table students 会发现create_time 字段默认是null而不是current_timestamp,虽然可以正常使用,但是不推荐 # second 颠倒 update_time 和 create_time 两个字段的顺序 # create_time = Column(TIMESTAMP(True),nullable=False,server_default=text("current_timestamp")) # create_time = Column(TIMESTAMP(True),nullable=False,server_default=text("now()")) # create_time = Column(TIMESTAMP(True),nullable=False,default=datetime.datetime.now()) # error 会有 on update current_timestamp语句 # update_time = Column(TIMESTAMP(True),nullable=False,server_default=text("current_timestamp on update current_timestamp")) # update_time = Column(TIMESTAMP(True),nullable=False,server_default=text("now() on update current_timestamp")) # third error # 该例证明了直接颠倒两个字段会失败的. # create_time = Column(TIMESTAMP(True),nullable=False,server_default=text("current_timestamp")) # update_time = Column(TIMESTAMP(True),nullable=False) Base.metadata.drop_all(engine) Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) sess = Session() zhangsan = Student(name='张三') sess.add(zhangsan) sess.commit() time.sleep(10) zhangsan_1 = sess.query(Student).get(1) zhangsan_1.name = 'lisi' sess.commit() wangwu = Student(name='wangwu') sess.add(wangwu) sess.commit()
浙公网安备 33010602011771号