python操作三大主流数据库(3)python操作mysql③python操作mysql的orm工具sqlaichemy安装配置和使用
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安装配置和使用的更多相关文章
- python操作三大主流数据库(14)python操作redis之新闻项目实战②新闻数据的展示及修改、删除操作
python操作三大主流数据库(14)python操作redis之新闻项目实战②新闻数据的展示及修改.删除操作 项目目录: ├── flask_redis_news.py ├── forms.py ├ ...
- python操作三大主流数据库(12)python操作redis的api框架redis-py简单使用
python操作三大主流数据库(12)python操作redis的api框架redis-py简单使用 redispy安装安装及简单使用:https://github.com/andymccurdy/r ...
- Python操作三大主流数据库☝☝☝
Python操作三大主流数据库☝☝☝ Python 标准数据库接口为 Python DB-API,Python DB-API为开发人员提供了数据库应用编程接口. Python 数据库接口支持非常多的数 ...
- Python操作三大主流数据库✍✍✍
Python操作三大主流数据库 Python 标准数据库接口为 Python DB-API,Python DB-API为开发人员提供了数据库应用编程接口. Python 数据库接口支持非常多的数据库, ...
- python操作三大主流数据库(8)python操作mongodb数据库②python使用pymongo操作mongodb的增删改查
python操作mongodb数据库②python使用pymongo操作mongodb的增删改查 文档http://api.mongodb.com/python/current/api/index.h ...
- python操作三大主流数据库(4)python操作mysql④python服务端flask和前端bootstrap框架结合实现新闻展示
python操作mysql④python服务端flask和前端bootstrap框架结合实现新闻展示 参考文档http://flask.pocoo.org/docs/0.11/http://flask ...
- python操作三大主流数据库(2)python操作mysql②python对mysql进行简单的增删改查
python操作mysql②python对mysql进行简单的增删改查 1.设计mysql的数据库和表 id:新闻的唯一标示 title:新闻的标题 content:新闻的内容 created_at: ...
- Python操作三大主流数据库
Python 标准数据库接口为 Python DB-API,Python DB-API为开发人员提供了数据库应用编程接口. Python 数据库接口支持非常多的数据库,你可以选择适合你项目的数据库: ...
- python操作三大主流数据库(10)python操作mongodb数据库④mongodb新闻项目实战
python操作mongodb数据库④mongodb新闻项目实战 参考文档:http://flask-mongoengine.readthedocs.io/en/latest/ 目录: [root@n ...
随机推荐
- spring注解第04课 @Import
1.beans package com.atguigu.bean; public class Blue { public Blue(){ System.out.println("blue.. ...
- RMQ st算法 区间最值模板
#include<bits/stdc++.h> ; ; int f[N][Logn],a[N],lg[N],n,m; int main(){ cin>>n>>m; ...
- 关于PHP中的全局变量global和$GLOBALS的不同区分
1.global Global的作用是定义全局变量,但是这个全局变量不是应用于整个网站,而是应用于当前页面,包括include或require的所有文件. 但是在函数体内定义的global变量,函数体 ...
- [C++]头文件<algorithm>
本博文仅示例一些常用的函数: sort.for_each. 1. sort /* STL - <algorithm> - sort template< class RandomIt, ...
- Restful API学习Day3 - DRF视图
视图 一.进化 class GenericView(APIView): """把视图中可能用到的配置和方法封装起来""" queryset ...
- extern 关键字使用
extern可以置于变量或者函数前,以标示变量或者函数的定义在别的文件中,提示编译器遇到此变量和函数时在其他模块中寻找其定义.此外extern也可用来进行链接指定. 如在头文件中: extern in ...
- Coursera, Machine Learning, Unsupervised Learning, K-means, Dimentionality Reduction
Clustering K-means: 基本思想是先随机选择要分类数目的点,然后找出距离这些点最近的training data 着色,距离哪个点近就算哪种类型,再对每种分类算出平均值,把中心点移动到 ...
- Linux环境及基础命令(一)
Linux环境及基础命令 一.认识Linux系统 略 二.配置Linux系统远程登录 2.1虚拟机系统配置 2.11虚拟机配置 统一NAT模式 虚拟机连不上 确定VMnet8网卡的IP地址(每台虚拟机 ...
- 【mmall】mybatis三剑客
mybatis-generator mybatis-plugin Mybatis Plugin插件安装破解及使用:http://blog.csdn.net/u011410529/article/det ...
- java.lang.Enum
参考博客链接 java枚举类型的优势在哪里? Java 枚举(enum) 详解7种常见的用法