python操作mysql③python操作mysql的orm工具sqlaichemy安装配置和使用

手册地址:
http://docs.sqlalchemy.org/en/rel_1_1/orm/index.html 安装
D:\software\source_tar>pip install SQLALchemy 检测是否安装成功
D:\software\source_tar>python
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlalchemy mysql的orm库SQLALchemy的操作 #coding:utf-8 from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, DateTime, Boolean
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker '''
id int primary key auto_increment,
title varchar(200) not null,
content varchar(2000) not null,
tpes varchar(10) not null,
image varchar(300) null,
author varchar(20) null,
view_count int default 0,
created_at datetime null,
is_valid smallint default 1
'''
# 创建对象的基类
Base = declarative_base()
# 初始化数据库连接,注意要接上charset=utf8否则中文无法支持
engine = create_engine("mysql://root:@localhost/news?charset=utf8")
# 创建DBSession类型
DBSession = sessionmaker(bind=engine) # 定义News对象
class News(Base):
__tablename__ = 'news'
id = Column(Integer, primary_key=True)
title = Column(String(200), nullable=False)
content = Column(String(2000), nullable=False)
types = Column(String(10), nullable=False)
image = Column(String(300),)
author = Column(String(20),)
view_count = Column(Integer)
created_at = Column(DateTime)
is_valid = Column(Boolean) '''
# 简单测试
# 如果表不存在就创建表
Base.metadata.create_all(engine) # 创建session对象:
session = DBSession()
# 创建新User对象,新增一条测试数据
news01 = News(title='标题1', content = 'content01', types = 'baidu',
image = '/static/img/01.jpg', author = 'jack', view_count = 3)
# 添加到session:
session.add(news01)
# 提交即保存到数据库:
session.commit()
# 关闭session:
session.close()
''' # orm的测试类
class OrmTest(object):
# 初始化创建session
def __init__(self):
self.session = DBSession() # 添加数据
def add_one(self):
new_obj = News(
title = '标题20180202',
content = '内容20180202',
types = '百家'
)
self.session.add(new_obj)
self.session.commit()
return new_obj # 添加多条数据
def add_more(self):
add_list = []
for i in range(10):
new_obj = News(title='标题%s'%str(i),content='内容%s'%str(i),types='百家%s'%str(i))
self.session.add(new_obj)
add_list.append(new_obj)
self.session.commit()
return add_list # 删除数据
def delete_data(self):
data = self.session.query(News).get(51)
self.session.delete(data)
self.session.commit() # 修改单条数据
def update_one(self, _id):
obj = self.session.query(News).get(_id)
if obj:
obj.is_valid = 0
self.session.add(obj)
self.session.commit()
return True return False # 修改多条数据
def update_data(self):
# filter_by的使用方法
# data_list = self.session.query(News).filter_by(is_valid = 0) # filter的使用方法
data_list = self.session.query(News).filter(News.id > 45)
for data in data_list:
print(data.title)
data.is_valid = 1
self.session.add(data)
self.session.commit() # 获取一条数据
def get_one(self):
return self.session.query(News).get(1) # 获取多条数据
def get_more(self):
return self.session.query(News).filter_by(is_valid = 1) def main():
obj = OrmTest()
# rst = obj.add_one()
# print('id:%s, title:%s,content:%s,types = %s' % (rst.id,rst.title,rst.content,rst.types)) # 添加多条数据
# rst = obj.add_more()
# for _new in rst:
# print('id:{0},title{1},content:{2}'.format(_new.id,_new.title,_new.content)) # 测试删除
# obj.delete_data() # 修改单条数据
# print(obj.update_one(50)) # 修改多条数据
obj.update_data() # 测试获取一条数据的函数
# rst = obj.get_one()
# print(rst.title) # 获取多条数据
# rst = obj.get_more()
# for _news in rst:
# print('news id: %s, title:%s, content:%s' % (_news.id,_news.title,_news.content)) if __name__ == "__main__":
main()

python操作三大主流数据库(3)python操作mysql③python操作mysql的orm工具sqlaichemy安装配置和使用的更多相关文章

  1. python操作三大主流数据库(14)python操作redis之新闻项目实战②新闻数据的展示及修改、删除操作

    python操作三大主流数据库(14)python操作redis之新闻项目实战②新闻数据的展示及修改.删除操作 项目目录: ├── flask_redis_news.py ├── forms.py ├ ...

  2. python操作三大主流数据库(12)python操作redis的api框架redis-py简单使用

    python操作三大主流数据库(12)python操作redis的api框架redis-py简单使用 redispy安装安装及简单使用:https://github.com/andymccurdy/r ...

  3. Python操作三大主流数据库☝☝☝

    Python操作三大主流数据库☝☝☝ Python 标准数据库接口为 Python DB-API,Python DB-API为开发人员提供了数据库应用编程接口. Python 数据库接口支持非常多的数 ...

  4. Python操作三大主流数据库✍✍✍

    Python操作三大主流数据库 Python 标准数据库接口为 Python DB-API,Python DB-API为开发人员提供了数据库应用编程接口. Python 数据库接口支持非常多的数据库, ...

  5. python操作三大主流数据库(8)python操作mongodb数据库②python使用pymongo操作mongodb的增删改查

    python操作mongodb数据库②python使用pymongo操作mongodb的增删改查 文档http://api.mongodb.com/python/current/api/index.h ...

  6. python操作三大主流数据库(4)python操作mysql④python服务端flask和前端bootstrap框架结合实现新闻展示

    python操作mysql④python服务端flask和前端bootstrap框架结合实现新闻展示 参考文档http://flask.pocoo.org/docs/0.11/http://flask ...

  7. python操作三大主流数据库(2)python操作mysql②python对mysql进行简单的增删改查

    python操作mysql②python对mysql进行简单的增删改查 1.设计mysql的数据库和表 id:新闻的唯一标示 title:新闻的标题 content:新闻的内容 created_at: ...

  8. Python操作三大主流数据库

    Python 标准数据库接口为 Python DB-API,Python DB-API为开发人员提供了数据库应用编程接口. Python 数据库接口支持非常多的数据库,你可以选择适合你项目的数据库:  ...

  9. python操作三大主流数据库(10)python操作mongodb数据库④mongodb新闻项目实战

    python操作mongodb数据库④mongodb新闻项目实战 参考文档:http://flask-mongoengine.readthedocs.io/en/latest/ 目录: [root@n ...

随机推荐

  1. redis集群之哨兵模式【原】

    redis集群之哨兵(sentinel)模式 哨兵模式理想状态 需要>=3个redis服务,>=3个redis哨兵,每个redis服务搭配一个哨兵. 本例以3个redis服务为例: 一开始 ...

  2. 【leetcode-71】 简化路径

    (1 pass) 以 Unix 风格给出一个文件的绝对路径,你需要简化它.或者换句话说,将其转换为规范路径. 在 Unix 风格的文件系统中,一个点(.)表示当前目录本身:此外,两个点 (..) 表示 ...

  3. 804. Unique Morse Code Words

    Description International Morse Code defines a standard encoding where each letter is mapped to a se ...

  4. weui hd bd ft

    weui样式看到hd ,bd, ft hd 是header的缩写 bd 是body的缩写 ft 是footer的缩写

  5. 解决XP系统任务管理器显示不全

    我们在使用电脑的时候有的时候打开任务管理器会发现任务管理器显示不全. 当碰到这种情况怎么解决呢?任务管理器显示不全的原因又是那些呢? 这里就来为大家分享下为什么任务管理器会显示不全以及如何解决这个问题 ...

  6. luogu 2704 炮兵阵地 状压dp

    状压的基础题吧 第一次看感觉难上天,后来嘛就.. 套路:先根据自身状态筛出可行状态,再根据地图等其他限制条件筛选适合的状态加入答案 f i,j,k 分别代表 行数,本行状态,上行状态,再累加答案即可 ...

  7. 【U3d】Tiled2Unity 使用Tips

    Tiled编辑完地图后借Tiled2Unity导入Unity. 使用T2U时遇到点麻烦,打开T2U界面显示如下,注意上方黄底文字,需要在Tiled中添加命令行才能使用T2U. 在Tiled工具栏点击( ...

  8. 【游记】关于NOIP2017

    -2017.11.13- Day0.到达酒店无所事事.跟着两个大佬拉着窗帘玩恐怖游戏留下了心理阴影,然后跑去找葱葱一起复习.晚上很晚才睡.Day1.T1结论题,以前写过.T2模拟,细节有点多.T3Di ...

  9. JS中attribute和property的区别

    attribute是HTML标签上的特性,它的值只能够是字符串:html 上id,class property是JavaScript里定义的对象: 如var  obj={x:1,y:2}  ,这里x, ...

  10. 【Vue】中 $attrs 中的使用方法

    vue官网是这样介绍的: 包含了父作用域中不作为 prop 被识别 (且获取) 的特性绑定 (class 和 style 除外).当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定 ( ...