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 ...
随机推荐
- room 二分图最大匹配KM
#include<bits/stdc++.h> #define fi first #define se second #define INF 0x3f3f3f3f #define fio ...
- notepad++查看二进制文件
1.进入以下网址去下载 https://sourceforge.net/projects/npp-plugins/files/Hex%20Editor/Hex%20Editor%20Plugin%20 ...
- Multiple APK Support
[Multiple APK Support] Multiple APK support is a feature on Google Play that allows you to publish d ...
- jquery不能实时获取CKEDITOR值的解决方法
不用传统的获取值的方法: var ckeditor = document.getElementById("ckeditor").value; 换成: var ckeditor = ...
- 第十章 优先级队列 (xa3)左式堆:插入与删除
- windows2008 r2 不能启用网络发现解决方法
1.出现的问题: 在“网络和共享中心”-“网络发现”不论如何,“启用”网络发现功能,系统都会自动重置为关闭状态. 2.解决方法: 运行中输入 services.msc-->在里边找到下边上个服务 ...
- 11. Container With Most Water(头尾双指针)
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). ...
- phpword根据模板导出word
参考网址:http://phpword.readthedocs.io/en/latest/installing.html 在composer.json中添加 { "require" ...
- angular小技巧随笔
1. 重新刷新页面 同页面切换状态: $state.go('tab.index', {inviteId:inviteId}); self.location.reload();
- f5会话保持
B/S架构的建议选择 inset cookie :c/s架构的 建议选择 sorce ip 1. Introduction to session persistence profiles Using ...