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. windows10下TensorFlow安装记录

    1.安装anaconda 安装最新版:https://repo.anaconda.com/archive/Anaconda3-5.3.0-Windows-x86_64.exe 加入环境变量: path ...

  2. 细说REST API安全之防止数据篡改

    通常可以使用MD5或SHA-1对API参数进行签名,在服务器端通过校验签名结果来验证数据是否被修改. 举个例子:添加用户 地址:http://192.168.0.10/v1/user/add?sign ...

  3. 【转载】详解KMP算法

    网址:https://www.cnblogs.com/yjiyjige/p/3263858.html

  4. js 日期 相关

    Js计算指定日期加上多少天.加多少月.加多少年的日期 function DateAdd(interval, number, date) { switch (interval) { case " ...

  5. SQL Server进阶(三)单表查询

    示例数据库 点我下载 一条完整的sql语句 select top | distinct 字段, 表达式, 函数, ... from 表表达式 where 筛选条件 group by 分组条件 havi ...

  6. java.lang.NoClassDefFoundError: org/apache/commons/collections/FastHashMap-----commons-ctions版本问题

    今天用到了一系列的第三方jar包,一环扣一环, 记住一个: 倘若你所导入的第三方jar包中的类一直显示未找到,那就是你的路径出问题了, /WEB-INF/lib目录下才是放第三方jar包位置, 但是今 ...

  7. oracle 启动em (使用浏览器打开)

    在cmd命令中执行 emctl status dbconsole 如果报错,确实oracle_UNQNAME 这个时候需要设置变量 oracle_hostname 和oracle_unqname 执行 ...

  8. Restful API学习Day3 - DRF视图

    视图 一.进化 class GenericView(APIView): """把视图中可能用到的配置和方法封装起来""" queryset ...

  9. Subsequences in Substrings Kattis - subsequencesinsubstrings (暴力)

    题目链接: Subsequences in Substrings Kattis - subsequencesinsubstrings 题目大意:给你字符串s和t.然后让你在s的所有连续子串中,找出这些 ...

  10. Centos7 nginx报错403 forbidden

    参考链接:http://www.cnblogs.com/chinway/archive/2017/08/14/7356239.html 因为安全性的考虑这个也是默认会出现的错误,因为SELinux的存 ...