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()
sqlalchemy学习-- 重要参数的更多相关文章
- SQLAlchemy 学习笔记(二):ORM
照例先看层次图 一.声明映射关系 使用 ORM 时,我们首先需要定义要操作的表(通过 Table),然后再定义该表对应的 Python class,并声明两者之间的映射关系(通过 Mapper). 方 ...
- 学习JVM参数前必须了解的
JVM参数是什么 大家照相通常使用手机就够用了,但是针对发烧友来说会使用更专业的设备,比如单反相机,在单反里有好几个模式,P/A/S/M,其中P是傻瓜模式,程序会自动根据环境设置快门速度和光圈大小,以 ...
- sqlAlchemy学习 001
研究学习主题 sqlAlchemy架构图 测试练习代码编写 连接数据库 看代码 db_config = { 'host': 'xxx.xxx.xxx.xx', 'user': 'root', 'pas ...
- SQLAlchemy 学习笔记(一):Engine 与 SQL 表达式语言
个人笔记,如有错误烦请指正. SQLAlchemy 是一个用 Python 实现的 ORM (Object Relational Mapping)框架,它由多个组件构成,这些组件可以单独使用,也能独立 ...
- sqlalchemy学习
sqlalchemy官网API参考 原文作为一个Pythoner,不会SQLAlchemy都不好意思跟同行打招呼! #作者:笑虎 #链接:https://zhuanlan.zhihu.com/p/23 ...
- TypeScript 学习一 参数,函数,析构表达式
1,TypeScript是由谷歌开发的,并且新出的Angular2框架就是谷歌公司由TypeScript语言编写的,所以现在TypeScript是有微软和谷歌一起支持的: 2,TypeScript在j ...
- shell脚本学习- 传递参数
跟着RUNOOB网站的教程学习的笔记 我们可以在执行shell脚本时,向脚本传递参数,脚本内获取参数的格式为:$n.n代表一个数字,1为执行脚本的第一参数,2为执行脚本的第二个参数,以此类推... 实 ...
- 深度学习:参数(parameters)和超参数(hyperparameters)
1. 参数(parameters)/模型参数 由模型通过学习得到的变量,比如权重和偏置 2. 超参数(hyperparameters)/算法参数 根据经验进行设定,影响到权重和偏置的大小,比如迭代次数 ...
- SQLAlchemy 学习笔记(三):ORM 中的关系构建
个人笔记,不保证正确. 关系构建:ForeignKey 与 relationship 关系构建的重点,在于搞清楚这两个函数的用法.ForeignKey 的用法已经在 SQL表达式语言 - 表定义中的约 ...
随机推荐
- time random sys os 模块
时间模块 在Python中,通常有这三种方式来表示时间:时间戳.元组(struct_time).格式化的时间字符串: (1)时间戳(timestamp) :通常来说,时间戳表示的是从1970年1月1日 ...
- 网络基础和python(二)
一,五层协议 应用层 端口 传输层 tcp\udp 网络层 ipv4\6 数据链路层 ethernet 物理层 mac 二:什么是变量? 变量:核心在于变和量儿字,变->变 ...
- OSB格式(REST)转化(XML到JSON,JSON到XML)
OSB转换项目操作手册 新建一个OSB项目 建立以下文件夹,以便更规范的管理工程 一.XML转JSON 1.导入wsdl文件 1)右键wsdl文件夹,选择import选项 2)在弹出框中选择Servi ...
- 【Selenium-WebDriver自学】WebDriver交互代码(十一)
==================================================================================================== ...
- js --- 关于DOM的事件操作
一.JavaScript的组成 JavaScript基础分为三个部分: ECMAScript:JavaScript的语法标准.包括变量.表达式.运算符.函数.if语句.for语句等. DOM:文档对象 ...
- C#分解质因数
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace app ...
- [UGUI]图文混排(七):动态表情
帧动画脚本: http://www.cnblogs.com/lyh916/p/9194823.html 这里的动态表情,我使用的是固定间隔去刷新Image上的Sprite来实现的,即帧动画.这里可以将 ...
- 【学习】Python解决汉诺塔问题
参考文章:http://www.cnblogs.com/dmego/p/5965835.html 一句话:学程序不是目的,理解就好:写代码也不是必然,省事最好:拿也好,查也好,解决问题就好! ...
- python中的popitem
popitem()随机删除字典中的任意键值对,并返回到元组中 1 a = { 2 "name":"dlrb", 3 "age":25, 4 ...
- apache 重点难点
apache 重点难点 在于难以理解其工作原理,因为它是c 写的:其模块众多:功能强大而复杂. 其配置也是格式不齐, 比如一下子是 key value , 一下子就成了 xml. 转载: http:/ ...