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. HDU 1016(素数环 深搜)

    题意是说对一个长度为 n 的数环进行排列,使得相邻两数的和为素数,按从小到大的顺序依次输出. 因为是环,所以总能调整成以 1 为序列首输出.用深度优先搜索的方法即可.在判断素数时由于 n 小于 20, ...

  2. 爬虫基础02-day24

    写在前面 上课第24天,打卡: 努力不必让全世界知道: s16/17爬虫2 内容回顾: 1. Http协议 Http协议:GET / http1.1/r/n...../r/r/r/na=1 TCP协议 ...

  3. 安装Blend+SketchFlow Preview for Visual Studio 2012出现错误

    安装Blend+SketchFlow Preview for Visual Studio 2012出现如下错误: 首先是这个网址:http://msdn.microsoft.com/en-us/exp ...

  4. 开发更健壮python程序的一些工具

    在众多语言中, Java 生态系统发展得最好, 比如异常logging报警, 比如性能监控工具. Python其实生态也不错, 这里列出一些出色的工具. LogBook, 并结合 raven-pyth ...

  5. Vue 限制input输入 限数字 或 小数点后两位number

    Vue 限制input输入 小数点后两位number <input type="number" @keydown="handleInput2" place ...

  6. error.c

    #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <string.h> ...

  7. javascript文件加载模式与加载方法

    加载方式 形象图像化方法,见 http://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html 1. script标签, ...

  8. [C++]2-5 分数化小数

    /* 分数化小数 输入正整数a,b,c,输出a/b的小数形式.精确到小数点后C位.a,b<=10^6,c<=10^6. 输入包含多组数据,结束标记为a=b=c=0 样例输入: 1 6 4 ...

  9. CentOS7清理磁盘空间

    1 首先查询磁盘空间占用情况. 发现/根目录下面磁盘占用百分之一百 df -ah 2 进入根目录,查询大文件与目录 cd /du -sh * | sort -n 查看上GB的目录并且排序,可以用这个命 ...

  10. 5.21http网页基础

    1,HTML的由来: web网页开发的标准,由w3c万维网联盟组织制定的.是制作网页的规范标准,分为结构标准.表现标准.行为标准.结构:html.表现:css.行为:Javascript. 2,htm ...