MySQLdb模块用于连接mysql数据库。
基本操作
  1. # -*- coding: utf-8 -*-      
  2. #mysqldb      
  3. import time, MySQLdb      
  4.      
  5. #连接      
  6. conn=MySQLdb.connect(host="localhost",user="root",passwd="root",db="test",charset="utf8")    
  7. cursor = conn.cursor()      
  8.  
  9. #删除表  
  10. sql = "drop table if exists user"  
  11. cursor.execute(sql)  
  12.  
  13. #创建  
  14. sql = "create table if not exists user(name varchar(128) primary key, created int(10))"  
  15. cursor.execute(sql)  
  16.  
  17. #写入      
  18. sql = "insert into user(name,created) values(%s,%s)"    
  19. param = ("aaa",int(time.time()))      
  20. = cursor.execute(sql,param)      
  21. print 'insert',n      
  22.      
  23. #写入多行      
  24. sql = "insert into user(name,created) values(%s,%s)"    
  25. param = (("bbb",int(time.time())), ("ccc",33), ("ddd",44) )  
  26. = cursor.executemany(sql,param)      
  27. print 'insertmany',n      
  28.  
  29. #更新      
  30. sql = "update user set name=%s where name='aaa'"    
  31. param = ("zzz")      
  32. = cursor.execute(sql,param)      
  33. print 'update',n      
  34.      
  35. #查询      
  36. = cursor.execute("select * from user")      
  37. for row in cursor.fetchall():      
  38.     print row  
  39.     for r in row:      
  40.         print r      
  41.      
  42. #删除      
  43. sql = "delete from user where name=%s"    
  44. param =("bbb")      
  45. = cursor.execute(sql,param)      
  46. print 'delete',n      
  47.  
  48. #查询      
  49. = cursor.execute("select * from user")      
  50. print cursor.fetchall()      
  51.  
  52. cursor.close()      
  53.      
  54. #提交      
  55. conn.commit()  
  56. #关闭 
  57. conn.close()
  58.      

封装类操作

此处ConfigUtils工具类为Python配置工具类ConfigParser使用提供。在使用数据库连接时,建议每次调用利用try finally机制,做好资源回收。在对于异常处理时,其实不建议像如此处理。

异常处理,不要对大段代码捕获exception,而是要处理具体的异常,以便提高程序健壮性。

  1.  class DButils(object):
  2.     def __init__(self,filename,section):
  3.         super(DButils, self).__init__()
  4.         #read config
  5.         cfg = ConfigUtils(filename).config
  6.         self.cfg = cfg
  7.         self.section = section
  8.         #init mysql connection
  9.         self.conn= MySQLdb.connect(
  10.             host=cfg.get(section,'host'),
  11.             port = cfg.getint(section,'port'),
  12.             user=cfg.get(section,'user'),
  13.             passwd=cfg.get(section,'passwd'),
  14.             db=cfg.get(section,'db'),
  15.             connect_timeout=cfg.getint(section,'connect_timeout')
  16.         )
  17.         self.cur = self.conn.cursor()    
  18.      
  19.     def fetchmany(self,sql):
  20.         sql = sql.replace('{$db}',self.cfg.get(self.section,'db'))
  21.         try:
  22.             return self.cur.fetchmany(self.cur.execute(sql))
  23.         except Exception, e:
  24.             print traceback.print_exc()
  25.             print sql
  26.    
  27.     def fetchone(self,sql):
  28.         sql = sql.replace('{$db}',self.cfg.get(self.section,'db'))
  29.         try:
  30.             self.cur.execute(sql)
  31.             return self.cur.fetchone()
  32.         except Exception, e:
  33.             print traceback.print_exc()
  34.             print sql
  35.  
  36.     def create(self,sql):
  37.         try:
  38.             self.cur.execute(sql)
  39.             self.conn.commit()
  40.         except Exception, e:
  41.             print traceback.print_exc()
  42.  
  43.     def is_table_exit(self,tableName):
  44.         show_sql = 'show tables;'
  45.         try:
  46.             return tableName in self.cur.fetchmany(self.cur.execute(show_sql))
  47.         except Exception,e:
  48.             print traceback.print_exc()
  49.     def close_db(self):
  50.         self.cur.close()
  51.         self.conn.close()
  52.  
  53. db    = DButils('ini.cfg','src_db')
  54. try:
  55.     db.fetchone('select * from table limit 1')
  56. finally:
  57.     db.close_db()

Python数据库工具类MySQLdb使用的更多相关文章

  1. MySQL数据库工具类之——DataTable批量加入MySQL数据库(Net版)

    MySQL数据库工具类之——DataTable批量加入数据库(Net版),MySqlDbHelper通用类希望能对大家有用,代码如下: using MySql.Data.MySqlClient; us ...

  2. MinerDB.java 数据库工具类

    MinerDB.java 数据库工具类 package com.iteye.injavawetrust.miner; import java.sql.Connection; import java.s ...

  3. 【JDBC】Java 连接 MySQL 基本过程以及封装数据库工具类

    一. 常用的JDBC API 1. DriverManager类 : 数据库管理类,用于管理一组JDBC驱动程序的基本服务.应用程序和数据库之间可以通过此类建立连接.常用的静态方法如下 static ...

  4. Java调用Python脚本工具类

    [本文出自天外归云的博客园] 在网上查了很多方法都不成功,在google上搜到一篇文章,做了一些小修改,能够处理中文输出.提取一个运行python脚本的Java工具类如下: package com.a ...

  5. 工具类之数据库工具类:DBUtil(採用反射机制)

    常常操作数据库的码农们一定知道操作数据库是一项非常复杂的工作.它不仅要解决各种乱码的问题还要解决各种数据表的增删改查等的操作. 另外每次操作数据库都要用到数据库连接.运行SQL语句.关闭连接的操作.所 ...

  6. JDBC-自定义数据库工具类(DBService)

     写在前面的话:      (1)使用JDBC,必须要使用对应的jar包,该笔记中使用jar包:mysql-connector-java-5.1 .6-bin.jar      (2)使用连接池,一定 ...

  7. Java课程设计---创建数据库工具类

    1.传统的数据库操作 package com.java.mysql; import java.sql.Connection; import java.sql.DriverManager; import ...

  8. 数据库工具类 JdbcUtils

    什么时候自己创建工具类 如果一个功能经常用到 我们建议把这个功能做成工具类 创建JdbcUtils包含三个方法 1: 把几个字符串 定义为常量 2:得到数据库连接getConnection(); 3 ...

  9. python 数据库操作类

    #安装PyMySQL:pip3 install PyMySQL   #!/usr/bin/python3   #coding=utf-8   #数据库操作类     from  datetime  i ...

随机推荐

  1. room 二分图最大匹配KM

    #include<bits/stdc++.h> #define fi first #define se second #define INF 0x3f3f3f3f #define fio ...

  2. notepad++查看二进制文件

    1.进入以下网址去下载 https://sourceforge.net/projects/npp-plugins/files/Hex%20Editor/Hex%20Editor%20Plugin%20 ...

  3. Multiple APK Support

    [Multiple APK Support] Multiple APK support is a feature on Google Play that allows you to publish d ...

  4. jquery不能实时获取CKEDITOR值的解决方法

    不用传统的获取值的方法: var ckeditor = document.getElementById("ckeditor").value; 换成: var ckeditor =  ...

  5. 第十章 优先级队列 (xa3)左式堆:插入与删除

  6. windows2008 r2 不能启用网络发现解决方法

    1.出现的问题: 在“网络和共享中心”-“网络发现”不论如何,“启用”网络发现功能,系统都会自动重置为关闭状态. 2.解决方法: 运行中输入 services.msc-->在里边找到下边上个服务 ...

  7. 11. Container With Most Water(头尾双指针)

    Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). ...

  8. phpword根据模板导出word

    参考网址:http://phpword.readthedocs.io/en/latest/installing.html 在composer.json中添加 { "require" ...

  9. angular小技巧随笔

    1. 重新刷新页面 同页面切换状态: $state.go('tab.index', {inviteId:inviteId}); self.location.reload();

  10. f5会话保持

    B/S架构的建议选择 inset cookie :c/s架构的 建议选择 sorce ip 1.  Introduction to session persistence profiles Using ...