sqlalchemy - day1
Posted 在路上的少年
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sqlalchemy - day1相关的知识,希望对你有一定的参考价值。
一、Create engine
Database url规则: dialect+driver://username:password@host:port/database
echo: True表示cmd窗口显示出对应的SQL 脚本信息
1 from sqlalchemy import create_engine 2 3 # Database url: dialect+driver://username:password@host:port/database 4 # eq: mysql+pymysql://purk:max123@local/test 5 # 在内存中创建一个sqllite 6 # engine = create_engine(\'sqlite:///:memory:\', echo=True) 7 # F:/test.db 如果test.db不存在,则创建一个。 8 engine = create_engine(\'sqlite:///F:/test.db\', echo=True)
二、create mapping class
1 from sqlalchemy import Column, Integer, String, Table 2 from sqlalchemy.ext.declarative import declarative_base 3 4 Base = declarative_base() 5 6 7 class Person(Base): 8 __tablename__ = \'person\' 9 10 id = Column(Integer, primary_key=True) 11 name = Column(String(50)) 12 13 class User(Base): 14 __tablename__=\'user\' 15 16 id = Column(Integer, primary_key=True) 17 name = Column(String(50))
1 >>> Person.__table__ 2 Table(\'person\', MetaData(bind=None), Column(\'id\', Integer(), table=<person>, primary_key=True, nullable=False), Column(\'name\', String(length=50), table=<person>), schema=None) 3 4 >>> Person.metadata is User.metadata 5 True 6 7 >>> Person.metadata is Base.metadata 8 True
传统的mapper configuration 就不介绍了,因为不直观,而且代码量还长,下面只贴出官网的例子
1 from sqlalchemy import Table, MetaData, Column, Integer, String, ForeignKey 2 from sqlalchemy.orm import mapper 3 metadata = MetaData() 4 user = Table(\'user\', metadata, 5 Column(\'id\', Integer, primary_key=True), 6 Column(\'name\', String(50)), 7 Column(\'fullname\', String(50)), 8 Column(\'password\', String(12)) 9 ) 10 11 12 class User(object): 13 14 15 def __init__(self, name, fullname, password): 16 self.name = name 17 self.fullname = fullname 18 self.password = password 19 mapper(User, user)
三、Column
1. DataType
1) Integer
id = Column(Integer)
2) String
name = Column(String(50))
3) Boolean
gender = Column(Boolean)
1 person = Person(name=\'purk\', gender=0) 2 person1 = Person(name=\'purk1\', gender=11) 3 person2 = Person(name=\'purk2\', gender=-1) 4 # try: 5 # person3 = Person(name=\'purk3\', gender=\'123\') 6 # except Exception as e: 7 # print(\'boolean类型在数据库中对应的smartint或boolean类型,输入字符串是不对的\') 8 db.add_all([person, person1, person2]) 9 db.commit()
结果如下
1 person_1 = db.query(Person).filter(Person.name == \'purk\').first() 2 person_2 = db.query(Person).filter(Person.name == \'purk1\').first() 3 person_3 = db.query(Person).filter(Person.name == \'purk2\').first() 4 print(person_1.gender) 5 print(person_2.gender) 6 print(person_3.gender)
查询 结果如下,满足boolean类型的一贯判断,非0即1.
4) Date -> datetime.date()
赋值可以使用python的date对象,也可以直接使用日期的字符串\'2016-10-21\',不过从数据库里面取出来的结果集该字段一定是python的date类型,这样在json或xml序列化的时候会有问题。
birthday = Column(Date())
5) DateTime -> datetime.datetime() 同 Date.
create_date = Column(DateTime(), default=datetime.now) default: 默认值,相当于在为给定值时赋予的默认值
modify_date = Column(DateTime(), onupdate=datetime.now) onupdate:在每次update时默认赋予的值,注,如果该字段已经被赋值,则不会再用默认值
1 birthday = Column(Date()) 2 create_date = Column(DateTime(), default=datetime.now) 3 modify_date = Column(DateTime(), onupdate=datetime.now) 4 5 person = Person(name=\'purk\', gender=True, level=\'123\') 6 person1 = Person(name=\'purk1\', gender=False, level=0) 7 person2 = Person(name=\'purk2\', gender=False, level=1) 8 person3 = Person(name=\'purk3\', gender=False, level=4) 9 person4 = Person(name=\'purk4\', gender=-1, level=\'medium\') 10 db.add_all([person, person1, person2, person3, person4]) 11 db.commit() 12 13 db.query(Person).filter(Person.name == \'purk\').update({Person.birthday: date.today()}) 14 person_1 = db.query(Person).filter(Person.name == \'purk1\').first() 15 person_1.birthday = \'2016-10-27\' 16 person_1.modify_date = \'2016-10-27 15:00:05\' #update时给定值 17 db.merge(person_1) 18 db.commit()
结果如下
6) Enum
level_list = (\'low\', \'medium\', \'high\')
level = Column(Enum(*level_list))
1 person = Person(name=\'purk\', gender=True, level=\'123\') 2 person1 = Person(name=\'purk1\', gender=False, level=0) 3 person2 = Person(name=\'purk2\', gender=False, level=1) 4 person3 = Person(name=\'purk3\', gender=False, level=4) 5 person4 = Person(name=\'purk4\', gender=-1, level=\'medium\')
Enum的index是从1开始的,越界的或者值不在枚举列中的都保存为null了
7)Float
menoy = Column(Float())
8) Unicode
data = Column(Unicode(200)) #目前测试的是Unicode 和String是一样样的,值得注意的是这两类型赋值可以是Byte类型的。
1 name = Column(String(50)) 2 data = Column(Unicode(200)) 3 4 person = Person(name=\'purk撒旦法撒旦法\'.encode(), gender=True, level=\'123\', data=\'asdf123\') 5 person1 = Person(name=\'purk1\', gender=False, level=0, data=\'asdf123是打发斯蒂芬\'.encode()) 6 7 person_1 = db.query(Person).filter(Person.name == \'purk1\').first() 8 print(person_1.data)
结果是
主要且常用的type我总结了一下,不常用的和我没研究懂得就pass咯。。。
以上是关于sqlalchemy - day1的主要内容,如果未能解决你的问题,请参考以下文章
from flask_sqlalchemy import SQLAlchemy 无法创建数据库表,代码无报错,代码如下,python版本是3.5