Python数据库工具类MySQLdb使用
# -*- coding: utf-8 -*-
#mysqldb
import time, MySQLdb
#连接
conn=MySQLdb.connect(host="localhost",user="root",passwd="root",db="test",charset="utf8")
cursor = conn.cursor()
#删除表
sql = "drop table if exists user"
cursor.execute(sql)
#创建
sql = "create table if not exists user(name varchar(128) primary key, created int(10))"
cursor.execute(sql)
#写入
sql = "insert into user(name,created) values(%s,%s)"
param = ("aaa",int(time.time()))
n = cursor.execute(sql,param)
print 'insert',n
#写入多行
sql = "insert into user(name,created) values(%s,%s)"
param = (("bbb",int(time.time())), ("ccc",33), ("ddd",44) )
n = cursor.executemany(sql,param)
print 'insertmany',n
#更新
sql = "update user set name=%s where name='aaa'"
param = ("zzz")
n = cursor.execute(sql,param)
print 'update',n
#查询
n = cursor.execute("select * from user")
for row in cursor.fetchall():
print row
for r in row:
print r
#删除
sql = "delete from user where name=%s"
param =("bbb")
n = cursor.execute(sql,param)
print 'delete',n
#查询
n = cursor.execute("select * from user")
print cursor.fetchall()
cursor.close()
#提交
conn.commit()
#关闭
conn.close()
封装类操作
此处ConfigUtils工具类为Python配置工具类ConfigParser使用提供。在使用数据库连接时,建议每次调用利用try finally机制,做好资源回收。在对于异常处理时,其实不建议像如此处理。
class DButils(object):
def __init__(self,filename,section):
super(DButils, self).__init__()
#read config
cfg = ConfigUtils(filename).config
self.cfg = cfg
self.section = section
#init mysql connection
self.conn= MySQLdb.connect(
host=cfg.get(section,'host'),
port = cfg.getint(section,'port'),
user=cfg.get(section,'user'),
passwd=cfg.get(section,'passwd'),
db=cfg.get(section,'db'),
connect_timeout=cfg.getint(section,'connect_timeout')
)
self.cur = self.conn.cursor()
def fetchmany(self,sql):
sql = sql.replace('{$db}',self.cfg.get(self.section,'db'))
try:
return self.cur.fetchmany(self.cur.execute(sql))
except Exception, e:
print traceback.print_exc()
print sql
def fetchone(self,sql):
sql = sql.replace('{$db}',self.cfg.get(self.section,'db'))
try:
self.cur.execute(sql)
return self.cur.fetchone()
except Exception, e:
print traceback.print_exc()
print sql def create(self,sql):
try:
self.cur.execute(sql)
self.conn.commit()
except Exception, e:
print traceback.print_exc() def is_table_exit(self,tableName):
show_sql = 'show tables;'
try:
return tableName in self.cur.fetchmany(self.cur.execute(show_sql))
except Exception,e:
print traceback.print_exc()
def close_db(self):
self.cur.close()
self.conn.close() db = DButils('ini.cfg','src_db')
try:
db.fetchone('select * from table limit 1')
finally:
db.close_db()
Python数据库工具类MySQLdb使用的更多相关文章
- MySQL数据库工具类之——DataTable批量加入MySQL数据库(Net版)
MySQL数据库工具类之——DataTable批量加入数据库(Net版),MySqlDbHelper通用类希望能对大家有用,代码如下: using MySql.Data.MySqlClient; us ...
- MinerDB.java 数据库工具类
MinerDB.java 数据库工具类 package com.iteye.injavawetrust.miner; import java.sql.Connection; import java.s ...
- 【JDBC】Java 连接 MySQL 基本过程以及封装数据库工具类
一. 常用的JDBC API 1. DriverManager类 : 数据库管理类,用于管理一组JDBC驱动程序的基本服务.应用程序和数据库之间可以通过此类建立连接.常用的静态方法如下 static ...
- Java调用Python脚本工具类
[本文出自天外归云的博客园] 在网上查了很多方法都不成功,在google上搜到一篇文章,做了一些小修改,能够处理中文输出.提取一个运行python脚本的Java工具类如下: package com.a ...
- 工具类之数据库工具类:DBUtil(採用反射机制)
常常操作数据库的码农们一定知道操作数据库是一项非常复杂的工作.它不仅要解决各种乱码的问题还要解决各种数据表的增删改查等的操作. 另外每次操作数据库都要用到数据库连接.运行SQL语句.关闭连接的操作.所 ...
- JDBC-自定义数据库工具类(DBService)
写在前面的话: (1)使用JDBC,必须要使用对应的jar包,该笔记中使用jar包:mysql-connector-java-5.1 .6-bin.jar (2)使用连接池,一定 ...
- Java课程设计---创建数据库工具类
1.传统的数据库操作 package com.java.mysql; import java.sql.Connection; import java.sql.DriverManager; import ...
- 数据库工具类 JdbcUtils
什么时候自己创建工具类 如果一个功能经常用到 我们建议把这个功能做成工具类 创建JdbcUtils包含三个方法 1: 把几个字符串 定义为常量 2:得到数据库连接getConnection(); 3 ...
- python 数据库操作类
#安装PyMySQL:pip3 install PyMySQL #!/usr/bin/python3 #coding=utf-8 #数据库操作类 from datetime i ...
随机推荐
- Java多线程及线程状态转换
以下内容整理自:http://blog.csdn.net/wtyvhreal/article/details/44176369 线程:是指进程中的一个执行流程. 线程与进程的区别:每个进程都需要操作 ...
- 如何搭建python+selenium2+eclipse的环境
搭建python和selenium2的环境(windows) 1.下载并安装python(我用的是2.7的版本) 可以去python官网下载安装:http://www.python.org/getit ...
- 八 xml模块
xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml呀,至今很多传统公司如金融行业的很多系统的 ...
- flash as3.0 截图保存图片
import flash.display.MovieClip; import flash.events.MouseEvent; import flash.filesystem.*; ///////// ...
- 牛客练习赛19 E和F(签到就走系列)托米的饮料+托米搭积木
E题传送门:点我 F题传送门:点我 可爱的小托米得到了n瓶饮料. 但他不小心把开盖的工具弄丢了,所以他只能利用饮料瓶来开盖. 已知第i个瓶子的品牌为ai,且其能打开bi品牌的瓶子. 问有几瓶饮料托米无 ...
- 项目总结08:spring quartz 定时器Demo
将定时器用到的quartz.jar放在lip文件下 quartz.xml文件(完整) <?xml version="1.0" encoding="UTF-8&quo ...
- js文字展示各种滚动效果
js文字展示各种滚动效果:http://www.dowebok.com/demo/188/
- DataTable 作为ObjectDataSource的数据源
好像是不能直接实现的.不过我从网上找到了这样的方法: 比如在BLL层中,SubjectManager是我对Subject表的业务类,此类中包含了Subject表的增删改查等各种方法.在aspx 页面中 ...
- HelloWorld 基础语法
所有内容取自菜鸟教程 public class HelloWorld { /* 第一个Java程序 * 它将打印字符串 Hello World */ public stat ...
- day 10 函数名的运用,闭包,迭代器
函数名的本质 函数名本质上就是函数的内存地址 函数名的五种运用: 1.函数名是一个变量 def func(): print(666) print(func) # 函数的内存地址 <functio ...