python入门练习之如何连接数据库
!/usr/bin/python
-- coding: UTF-8 --
author = 'luke'
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import sessionmaker
import traceback
打开数据库连接
session_class = sessionmaker(bind=connect) # 创建与数据库的会话session class ,这里返回给session的是个class,不是实例
Base = declarative_base() # 生成ORM基类
##################User Class##################################
class User(Base):
tablename = "hello_word" # 表名
id = Column(String(255), primary_key=True)
score = Column(Integer)
sccess_times = Column(Integer)
fail_times = Column(Integer)
http_type = Column(String(255))
##################IpRate Class##################################
class IpRate(Base):
tablename = "ip_rate" # 表名
id = Column(String(255), primary_key=True)
fail_times = Column(Integer)
score = Column(Integer)
sccess_times = Column(Integer)
http_type = Column(String(255))
def _addOne(obj):
try:
session = session_class()
#新增一条数据
#原生sql:insert into mysql.hello_word(name,password) values("test2","1234");
#obj = User(id="127.0.0.1:8080", score=5,sccess_times=0,fail_times=0,http_type='http') #生成你要创建的数据对象
session.add(obj) #把要创建的数据对象添加到这个session里, 一会统一创建
session.commit() #统一提交,创建数据,在此之前数据库是不会有新增数据的
print('addOne ok...')
except:
session.rollback()
print ("Error: unable to addOne data")
finally:
session.close()
def _addAll(objlist):
'''
objlist: object list
'''
try:
session = session_class()
session.add_all(objlist) #把要创建的数据对象添加到这个session里, 一会统一创建
session.commit() #统一提交,创建数据,在此之前数据库是不会有新增数据的
except:
session.rollback()
print ("Error: unable to addAll data")
finally:
session.close()
def _del(obj):
'''
objlist: object list
'''
try:
session = session_class()
session.query(obj).delete() #通过session查询User类,然后过滤出id>5的进行删除
print ("_del...ok")
session.commit()
except:
session.rollback()
print ("Error: unable to delete data")
finally:
session.close()
def _updateOneById(obj,id,key,value):
try:
session = session_class()
data = session.query(obj).filter(id==id)
setattr(object=data,name=key,value=value)
session.commit()
print ("_updateOneById...ok")
except:
session.rollback()
print ("Error: unable to update data")
finally:
session.close()
def _fetchOneById(obj,id):
try:
session = session_class()
results = session.query(obj).filter(obj.idid)
if(len(results) > 0):
print ("_fetchOneById...ok")
return results[0]
else:
return None
except:
print ("Error: unable to _fetchOneById data")
finally:
session.close()
def _fetchAll(obj):
try:
session = session_class()
results = session.query(obj).all() #查询所有
if(len(results) > 0):
print ("_fetchAll...ok")
return results
else:
return None
except:
print ("Error: unable to _fetchAll data")
finally:
session.close()
if name'main':
try:
#Base.metadata.create_all(connect) # 创建表结构
#print('创建成功')
user = User(id='127.0.0.2:8080',score=10,sccess_times=0,fail_times=0,http_type='http')
# user.id = '127.0.0.1:8080'
# user.score = 10
# user.sccess_times = 0
# user.fail_times = 0
# user.http_type = 'http'
#_addOne(user)
data = _fetchOneById(User,'127.0.0.1:8080')
print(data)
data2 = _fetchAll(User)
_updateOneById(User,'127.0.0.1:8080','score',1)
_del(user)
except BaseException as e:
traceback.print_exc()
python入门练习之如何连接数据库的更多相关文章
- 6 小时 Python 入门
6 小时 Python 入门 以下操作均在 Windows 环境下进行操作,先说明一下哈 一.安装 Python 1.官网下载 Python 进入官网(https://www.python.org), ...
- python入门简介
Python前世今生 python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚本解释程序,作为ABC ...
- python入门学习课程推荐
最近在学习自动化,学习过程中,越来越发现coding能力的重要性,不会coding,基本不能开展自动化测试(自动化工具只是辅助). 故:痛定思痛,先花2个星期将python基础知识学习后,再进入自动化 ...
- Python运算符,python入门到精通[五]
运算符用于执行程序代码运算,会针对一个以上操作数项目来进行运算.例如:2+3,其操作数是2和3,而运算符则是“+”.在计算器语言中运算符大致可以分为5种类型:算术运算符.连接运算符.关系运算符.赋值运 ...
- Python基本语法[二],python入门到精通[四]
在上一篇博客Python基本语法,python入门到精通[二]已经为大家简单介绍了一下python的基本语法,上一篇博客的基本语法只是一个预览版的,目的是让大家对python的基本语法有个大概的了解. ...
- Python基本语法,python入门到精通[二]
在上一篇博客Windows搭建python开发环境,python入门到精通[一]我们已经在自己的windows电脑上搭建好了python的开发环境,这篇博客呢我就开始学习一下Python的基本语法.现 ...
- visual studio 2015 搭建python开发环境,python入门到精通[三]
在上一篇博客Windows搭建python开发环境,python入门到精通[一]很多园友提到希望使用visual studio 2013/visual studio 2015 python做demo, ...
- python入门教程链接
python安装 选择 2.7及以上版本 linux: 一般都自带 windows: https://www.python.org/downloads/windows/ mac os: https:/ ...
- Python学习【第二篇】Python入门
Python入门 Hello World程序 在linux下创建一个叫hello.py,并输入 print("Hello World!") 然后执行命令:python hello. ...
随机推荐
- review一个javascript功能函数
近半年来一直觉得自己在技术上好像左右挣扎,技术没啥提升,看书看不进,自学还挺慢.写出来的东西,自己都觉得不满意.让自己也用庸人自扰的感觉. 最近,在工作中,有一个小小的功能需要实现,这个功能非常简单, ...
- Lua的文件IO操作
Lua 标准库 - 输入输出处理(input and output facilities) 转载于:http://blog.csdn.net/duanxuyun 文本Tag: Lua [IT168 技 ...
- JavaScript语言精粹 笔记05 正则表达式
正则表达式 正则表达式以方法的形式被用于对字符串中的信息进行查找.替换画图提取操作.可处理正则表达式的方法有:regexp.exec, regexp.test,string.match, string ...
- 20169202 2016-2017-2《TCP/IP协议攻击》实验总结--十一周
APR缓存中毒(ARP cache poisoning) 实验原理 ARP缓存是ARP协议的重要组成部分.ARP协议运行的目标就是建立MAC地址和IP地址的映射,然后把这一映射关系保存在ARP缓存中, ...
- HTML inline 与block元素
行标签:内容撑开宽度,不可以控制宽和高,它的宽和高随标签里的内容而改变 块标签:撑满行(默认) ,可以用样式控制其宽和高 但行标签 img,textarea,select,input 是可以设置宽和高 ...
- 简单介绍Java的静态分派和动态分派
最近复习JVM的知识,对于静态分派和动态分派的理解有点混乱,于是自己尝试写写代码,在分析中巩固知识. 有如下一段代码,请问每一段分别输出什么? package com.khlin.my.test; c ...
- INDEX--索引页上存放那些数据
由于索引的叶子节点和非叶子节点的作用不同,导致不同类型节点上每行记录存放的数据不同--============================================唯一聚集索引叶子节点:所有 ...
- OCP认证052考试最新考试题库和答案整理-33
33.Where Is backup metadata stored for use by Recovery Manager (RMAN)? A) In the control file B) In ...
- php中使用PHPExcel读写excel(xls)文件的方法
首先从GitHub上下载 excel的相关类库 下载地址:https://github.com/PHPOffice/PHPExcel 以下是从excel中获取数据 <?php /** * * @ ...
- Postman使用手册1——导入导出和发送请求查看响应
导读: 现在的web和移动开发,常常会调用服务器提供restful接口进行数据请求,为了调试,一般会先用工具进行测试,通过测试后才开始在开发中使用.这里介绍一下如何在chrome浏览器利用postma ...