!/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入门练习之如何连接数据库的更多相关文章

  1. 6 小时 Python 入门

    6 小时 Python 入门 以下操作均在 Windows 环境下进行操作,先说明一下哈 一.安装 Python 1.官网下载 Python 进入官网(https://www.python.org), ...

  2. python入门简介

    Python前世今生 python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚本解释程序,作为ABC ...

  3. python入门学习课程推荐

    最近在学习自动化,学习过程中,越来越发现coding能力的重要性,不会coding,基本不能开展自动化测试(自动化工具只是辅助). 故:痛定思痛,先花2个星期将python基础知识学习后,再进入自动化 ...

  4. Python运算符,python入门到精通[五]

    运算符用于执行程序代码运算,会针对一个以上操作数项目来进行运算.例如:2+3,其操作数是2和3,而运算符则是“+”.在计算器语言中运算符大致可以分为5种类型:算术运算符.连接运算符.关系运算符.赋值运 ...

  5. Python基本语法[二],python入门到精通[四]

    在上一篇博客Python基本语法,python入门到精通[二]已经为大家简单介绍了一下python的基本语法,上一篇博客的基本语法只是一个预览版的,目的是让大家对python的基本语法有个大概的了解. ...

  6. Python基本语法,python入门到精通[二]

    在上一篇博客Windows搭建python开发环境,python入门到精通[一]我们已经在自己的windows电脑上搭建好了python的开发环境,这篇博客呢我就开始学习一下Python的基本语法.现 ...

  7. visual studio 2015 搭建python开发环境,python入门到精通[三]

    在上一篇博客Windows搭建python开发环境,python入门到精通[一]很多园友提到希望使用visual studio 2013/visual studio 2015 python做demo, ...

  8. python入门教程链接

    python安装 选择 2.7及以上版本 linux: 一般都自带 windows: https://www.python.org/downloads/windows/ mac os: https:/ ...

  9. Python学习【第二篇】Python入门

    Python入门 Hello World程序 在linux下创建一个叫hello.py,并输入 print("Hello World!") 然后执行命令:python hello. ...

随机推荐

  1. UVa 12342 Tax Calculator (水题,纳税)

    今天在uva看到一个水题,分享一下. 题意:制定纳税的总额,有几个要求,如果第一个180000,不纳,下一个300000,纳10%,再一个400000,纳15%,再一个300000,纳20%,以后的纳 ...

  2. Mysql自动设置时间(自动获取时间,填充时间)

    应用场景: 1.在数据表中,要记录每条数据是什么时候创建的,不需要应用程序去特意记录,而由数据数据库获取当前时间自动记录创建时间: 2.在数据库中,要记录每条数据是什么时候修改的,不需要应用程序去特意 ...

  3. Acrobat_8_Pro_SC 激活老是提示你输入的授权码无效

    假如安装了Adobe Acrobat Professional 8 的时候无法激活, 或在恢复安装时 Adobe Acrobat Professional 8 需要重新激活, 激活的时候,总是提示你输 ...

  4. delphi实现截全屏功能

    procedure TForm1.Button10Click(Sender: TObject);var bmp: TBitmap; can: TCanvas; dc: HDC; Image1: TIm ...

  5. 关于C#/sqlserver生成32位数据库字段总结

    一.C#中用Guid.NewGuid().ToString() Sql中用NEWID()   以上方法生成的是36位的GUID,如果需要转换成32位,则需要替换掉其中的'-'字符. Sql中的方法:r ...

  6. Mysql链接字符串问题

    <add key="ConnstringMySql" value="server=xxx.xxx.xxx.xxx;database=YourDatabase;uid ...

  7. 关于react的一些疑问点

    参考转载:链接:http://www.jianshu.com/p/83bda9cd8c67 1.refs <input type="text" ref="input ...

  8. xshell远程连接虚拟机

    xshell百度网盘下载地址: 链接: https://pan.baidu.com/s/1cNn458wUyKNOcAxQ8vEPQg密码: 8vrw 安装xshell,步骤很简单这里就不多说了 if ...

  9. hdu3698 Let the light guide us(dp+线段树)

    题意:在每行上选一个点,每个点都要各自对应的代价,同时相邻两行的点要满足 |j-k|≤f(i,j)+f(i+1,k).问最小代价是多少. 题解: 不难发现这是一道dp,状态转移方程如下$dp[i][j ...

  10. 基于LDAP下的Samba服务

    基于LDAP下的Samba服务 一.环境情况: 实验环境:俩台机器,分别为2012R2,安装有 AD 并作为域控制器Domain Controller(DC),同时也作为 DNS 服务器和时间服务器: ...