python MySQLdb使用教程详解


Posted in Python onMarch 20, 2018

本文主要内容python MySQLdb数据库批量插入insert,更新update的:

1.python MySQLdb的使用,写了一个基类让其他的sqldb继承这样比较方便,数据库的ip, port等信息使用json配置文件

2.常见的查找,批量插入更新

python MySQLdb使用教程详解

下面贴出基类代码:

# _*_ coding:utf-8 _*_
import MySQLdb
import json
import codecs
# 这个自己改一下啊
from utils.JsonUtil import get_json_from_file
def byteify(input):
  """
  the string of json typed unicode to str in python
  This function coming from stack overflow
  :param input: {u'first_name': u'Guido', u'last_name': u'jack'}
  :return:   {'first_name': 'Guido', 'last_name': 'jack'}
  """
  if isinstance(input, dict):
    return {byteify(key): byteify(value)
        for key, value in input.iteritems()}
  elif isinstance(input, list):
    return [byteify(element) for element in input]
  elif isinstance(input, unicode):
    return input.encode('utf-8')
  else:
    return input
def get_json_from_file(filename):
  with open(filename) as jf:
    jsondata = json.load(jf)
  return byteify(jsondata)
class DbBase(object):
  def __init__(self, **kwargs):
    self.db_config_file = kwargs['db_config_file']
    self.config_db(self.db_config_file)
  def config_db(self, db_config_file):
    data = get_json_from_file(db_config_file)
    host = data['host']
    user = data['user']
    pwd = data['pwd']
    db = data['db']
    port = data['port']
    self.tb_audit_mobile = data['tb_audit_mobile']
    self.conn = MySQLdb.connect(host=host, port=port, user=user, passwd=pwd, db=db, charset="utf8", use_unicode=True)
    self.cursor = self.conn.cursor()

子类的示例:

class DbAuditTestService(DbBase):
  def __init__(self, **kwargs):
    super(DbAuditTestService, self).__init__(**kwargs)
  def getAdTestURl(self, beg, end):
    sql = """select url, source from tb_name where create_date BETWEEN '%s' and '%s' """ % (beg, end)
    self.cursor.execute(sql)
    res = [row for row in self.cursor]
    return res
  def insert(self, lst_row):
  """batch insert, use ignore 避免索引唯一问题"""
    try:
      insert_sql = 'INSERT ignore INTO tb_ms_mobile_report_test (appid, source) VALUES (%s, %s)'
      self.cursor.executemany(insert_sql, lst_row)
      self.conn.commit()
    except MySQLdb.OperationalError as e:
      logger.info('%s' % e)
      self.cursor.close()
      self.conn.close()
      self.config_db(self.db_config_file)
  def update_ip_info(self, ip_info):
    """
    batch update 
      [[voilate_right_rate, ip]]
    :param ip_info:
    :return:
    """
    query = """
        update tb_ms_audit_ip_info set
        ip_right_rate=%s
        where submit_ip=%s """
    self.cursor.executemany(query, ip_info)
    self.conn.commit()
def insert_all():
"""批量操作的示例"""
  db_audit = DbAuditService(db_config_file='../config/mysql_police_audit.json')
  size = db_audit.count()
  db_audit_test = DbAuditTestService(db_config_file='../config/mysql_local_audit.json')
  batch_size = 2000
  for k in xrange(100000, size, batch_size):
    logger.info('query limit %s ~ %s' % (k, batch_size))
    lst_row = db_audit.query_limit(k, batch_size)
    logger.info('convert_rows ')
    lst_row = convert_rows(lst_row)
    db_audit_test.insert(lst_row)

总结

以上所述是小编给大家介绍的python MySQLdb使用教程详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Python 相关文章推荐
使用python将mdb数据库文件导入postgresql数据库示例
Feb 17 Python
为Python的web框架编写MVC配置来使其运行的教程
Apr 30 Python
Python中用于检查英文字母大写的isupper()方法
May 19 Python
Python实现模拟登录及表单提交的方法
Jul 25 Python
python学习之编写查询ip程序
Feb 27 Python
python调用fortran模块
Apr 08 Python
Django中ORM表的创建和增删改查方法示例
Nov 15 Python
Python实现的本地文件搜索功能示例【测试可用】
May 30 Python
Django中使用session保持用户登陆连接的例子
Aug 06 Python
Python使用微信itchat接口实现查看自己微信的信息功能详解
Aug 22 Python
pygame实现非图片按钮效果
Oct 29 Python
Python IDE环境之 新版Pycharm安装详细教程
Mar 05 Python
django中的HTML控件及参数传递方法
Mar 20 #Python
安装python时MySQLdb报错的问题描述及解决方法
Mar 20 #Python
python如何定义带参数的装饰器
Mar 20 #Python
Python回文字符串及回文数字判定功能示例
Mar 20 #Python
python如何把嵌套列表转变成普通列表
Mar 20 #Python
Python内置函数reversed()用法分析
Mar 20 #Python
shell命令行,一键创建 python 模板文件脚本方法
Mar 20 #Python
You might like
thinkphp中连接oracle时封装方法无法用的解决办法
2013/06/17 PHP
php中array_multisort对多维数组排序的方法
2020/06/21 PHP
php生出随机字符串
2017/07/06 PHP
一样的table?不一样的table(可编辑状态table)
2012/09/19 Javascript
jquery中的常用事件bind、hover、toggle等示例介绍
2014/07/21 Javascript
jQuery中:checked选择器用法实例
2015/01/04 Javascript
jQuery删除一个元素后淡出效果展示删除过程的方法
2015/03/18 Javascript
jQuery实现判断滚动条到底部
2015/06/23 Javascript
jquery插件uploadify多图上传功能实现代码
2016/08/12 Javascript
Jquery给当前页或者跳转后页面的导航栏添加选中后样式的实例
2016/12/08 Javascript
微信小程序页面滑动屏幕加载数据效果
2020/11/16 Javascript
jQuery中的for循环var与let的区别
2018/04/21 jQuery
vue实现未登录跳转到登录页面的方法
2018/07/17 Javascript
微信小程序购物车、父子组件传值及calc的注意事项总结
2018/11/14 Javascript
小程序显示弹窗时禁止下层的内容滚动实现方法
2019/03/20 Javascript
javascript 设计模式之组合模式原理与应用详解
2020/04/08 Javascript
Vue Render函数创建DOM节点代码实例
2020/07/08 Javascript
在Python中移动目录结构的方法
2016/01/31 Python
【python】matplotlib动态显示详解
2019/04/11 Python
pycharm解决关闭flask后依旧可以访问服务的问题
2020/04/03 Python
利用三角函数在canvas上画虚线的方法
2018/01/11 HTML / CSS
沃达丰英国有限公司:Vodafone英国
2019/04/16 全球购物
Interrail法国:乘火车探索欧洲,最受欢迎的欧洲铁路通票
2019/08/27 全球购物
耐克波兰官方网站:Nike波兰
2019/09/03 全球购物
意大利包包和行李箱销售网站:Bagaglio.it
2021/03/02 全球购物
个人简历自我鉴定
2013/10/11 职场文书
实习自我鉴定范文
2013/10/30 职场文书
初二物理教学反思
2014/01/29 职场文书
三月学雷锋月活动总结
2014/04/28 职场文书
党校毕业心得体会
2014/09/13 职场文书
奉献家乡演讲稿
2014/09/16 职场文书
2014国庆节幼儿园亲子活动方案
2014/09/16 职场文书
向雷锋同志学习倡议书
2015/04/27 职场文书
90后经典动画片排行:《数码宝贝》第二,《小鲤鱼历险记》在榜
2022/03/18 日漫
世界十大狙击步枪排行榜
2022/03/20 杂记
《总之就是很可爱》新作短篇动画《总之就是很可爱~制服~》将于2022年夏天播出
2022/04/07 日漫