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中字典的键的使用
Aug 19 Python
Python和Perl绘制中国北京跑步地图的方法
Mar 03 Python
浅谈python numpy中nonzero()的用法
Apr 02 Python
Python实现统计给定列表中指定数字出现次数的方法
Apr 11 Python
Python设置在shell脚本中自动补全功能的方法
Jun 25 Python
pandas使用get_dummies进行one-hot编码的方法
Jul 10 Python
使用python socket分发大文件的实现方法
Jul 08 Python
python numpy实现rolling滚动案例
Jun 08 Python
python import 上级目录的导入
Nov 03 Python
python 爬虫爬取京东ps4售卖情况
Dec 18 Python
Python实现Telnet自动连接检测密码的示例
Apr 16 Python
python绘制箱型图
Apr 27 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
php 判断网页是否是utf8编码的方法
2014/06/06 PHP
php源码分析之DZX1.5字符串截断函数cutstr用法
2015/06/17 PHP
Yii框架中sphinx索引配置方法解析
2016/10/18 PHP
CSS中简写属性要注意TRouBLe的顺序问题(避免踩坑)
2021/03/09 HTML / CSS
Javascript 布尔型分析
2008/12/22 Javascript
修改jQuery.Autocomplete插件 支持中文输入法 避免TAB、ENTER键失效、导致表单提交
2009/10/11 Javascript
jquery 学习之二 属性(类)
2010/11/25 Javascript
用jquery模仿的a的title属性的例子
2014/10/22 Javascript
基于jQuery全屏焦点图左右切换插件responsiveslides
2015/09/07 Javascript
JavaScript实现的微信二维码图片生成器的示例
2016/10/26 Javascript
JS实现针对给定时间的倒计时功能示例
2017/04/11 Javascript
微信小程序中插入激励视频广告并获取收益(实例代码)
2019/12/06 Javascript
Vue中实现回车键切换焦点的方法
2020/02/19 Javascript
python获取指定路径下所有指定后缀文件的方法
2015/05/26 Python
Python协程 yield与协程greenlet简单用法示例
2019/11/22 Python
最新2019Pycharm安装教程 亲测
2020/02/28 Python
celery在python爬虫中定时操作实例讲解
2020/11/27 Python
Lookfantastic挪威官网:英国知名美妆购物网站
2017/07/26 全球购物
英国排名第一的在线宠物用品商店:Monster Pet Supplies
2018/05/20 全球购物
中专毕业个人的自荐信格式
2013/09/21 职场文书
银行柜员应聘推荐信范文
2013/11/24 职场文书
计算机毕业大学生推荐信
2013/12/01 职场文书
采购内勤岗位职责
2013/12/10 职场文书
大二法学专业职业生涯规划范文
2014/02/12 职场文书
大班上学期幼儿评语
2014/04/30 职场文书
我的老师教学反思
2014/05/01 职场文书
揭牌仪式策划方案
2014/05/28 职场文书
员工安全生产责任书
2014/07/22 职场文书
群众路线教育实践活动学习笔记内容
2014/11/06 职场文书
单位接收函范文
2015/01/30 职场文书
汽车4S店前台接待岗位职责
2015/04/03 职场文书
2015年小学体育工作总结
2015/05/22 职场文书
2016七夕情人节感言
2015/12/09 职场文书
导游词之河北野三坡
2019/12/11 职场文书
python自动化调用百度api解决验证码
2021/04/13 Python
基于tensorflow权重文件的解读
2021/05/26 Python