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实现从字符串中找出字符1的位置以及个数的方法
Aug 25 Python
用Python制作简单的朴素基数估计器的教程
Apr 01 Python
Python编程给numpy矩阵添加一列方法示例
Dec 04 Python
python pandas中DataFrame类型数据操作函数的方法
Apr 08 Python
8种用Python实现线性回归的方法对比详解
Jul 10 Python
关于Python中定制类的比较运算实例
Dec 19 Python
TensorFlow使用Graph的基本操作的实现
Apr 22 Python
浅谈anaconda python 版本对应关系
Oct 07 Python
opencv python 对指针仪表读数识别的两种方式
Jan 14 Python
Python .py生成.pyd文件并打包.exe 的注意事项说明
Mar 04 Python
python中tkinter复选框使用操作
Nov 11 Python
Python3使用Qt5来实现简易的五子棋小游戏
May 02 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将二维数组变为标签适用的一维数组方法总结
2014/10/30 PHP
PHP加密3DES报错 Call to undefined function: mcrypt_module_open() 如何解决
2016/04/17 PHP
Laravel中的Auth模块详解
2017/08/17 PHP
关于实现代码语法标亮 dp.SyntaxHighlighter
2007/02/02 Javascript
jquery库或JS文件在eclipse下报错问题解决方法
2014/04/17 Javascript
Angular用来控制元素的展示与否的原生指令介绍
2015/01/07 Javascript
jQuery实现鼠标划过展示大图的方法
2015/03/09 Javascript
JavaScript中exec函数用法实例分析
2015/06/08 Javascript
jQuery实现多级下拉菜单jDropMenu的方法
2015/08/28 Javascript
jQuery多条件筛选如何实现
2015/11/04 Javascript
jquery中ajax跨域方法实例分析
2015/12/18 Javascript
jQuery下拉框的简单应用
2016/06/24 Javascript
AngularJS页面带参跳转及参数解析操作示例
2017/06/28 Javascript
Vue动态组件实例解析
2017/08/20 Javascript
浅谈mint-ui loadmore组件注意的问题
2017/11/08 Javascript
JavaScript中变量提升与函数提升经典实例分析
2018/07/26 Javascript
jQuery实现适用于移动端的跑马灯抽奖特效示例
2019/01/18 jQuery
JavaScript实现的弹出遮罩层特效经典示例【基于jQuery】
2019/07/10 jQuery
[02:08]2014DOTA2国际邀请赛 430专访:力争取得小组前二
2014/07/11 DOTA
Python中的fileinput模块的简单实用示例
2015/07/09 Python
使用Python画出小人发射爱心的代码
2019/11/23 Python
Python Tornado实现WEB服务器Socket服务器共存并实现交互的方法
2020/05/26 Python
Html5页面获取微信公众号的openid的方法
2020/05/12 HTML / CSS
Sunglasses Shop荷兰站:英国最大的太阳镜独立在线零售商和供应商
2017/01/08 全球购物
法国房车租赁网站:Yescapa
2019/08/26 全球购物
酒店前厅员工辞职信
2014/01/08 职场文书
养殖项目策划书范文
2014/01/13 职场文书
高中数学教学反思
2014/01/30 职场文书
主办会计岗位职责
2014/03/13 职场文书
党员批评与自我批评思想汇报(集锦)
2014/09/14 职场文书
2015年教师见习期工作总结
2015/05/20 职场文书
MIME类型中application/xml与text/xml的区别介绍
2022/01/18 HTML / CSS
《异世界四重奏》剧场版6月10日上映 PV视觉图原创角色发表
2022/03/20 日漫
Python中第三方库Faker的使用详解
2022/04/02 Python
AJAX引擎原理以及XmlHttpRequest对象的axios、fetch区别详解
2022/04/09 Javascript
httpclient调用远程接口的方法
2022/08/14 Java/Android