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 相关文章推荐
linux环境下安装pyramid和新建项目的步骤
Nov 27 Python
python实现的用于搜索文件并进行内容替换的类实例
Jun 28 Python
通过Python爬虫代理IP快速增加博客阅读量
Dec 14 Python
python爬虫获取京东手机图片的图文教程
Dec 29 Python
使用Python+Splinter自动刷新抢12306火车票
Jan 03 Python
导入tensorflow时报错:cannot import name 'abs'的解决
Oct 10 Python
python用类实现文章敏感词的过滤方法示例
Oct 27 Python
解决pyCharm中 module 调用失败的问题
Feb 12 Python
自定义Django默认的sitemap站点地图样式
Mar 04 Python
Pycharm激活方法及详细教程(详细且实用)
May 12 Python
Python 如何在字符串中插入变量
Aug 01 Python
python Xpath语法的使用
Nov 26 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
从零开始学YII2框架(四)扩展插件yii2-kartikgii
2014/08/20 PHP
阿里云的WindowsServer2016上部署php+apache
2018/07/17 PHP
收集的10个免费的jQuery相册
2011/02/26 Javascript
详解Javascript 装载和执行
2014/11/17 Javascript
js实现横向伸展开的二级导航菜单代码
2015/08/28 Javascript
Bootstrap3 Grid system原理及应用详解
2016/09/30 Javascript
jQuery移除或禁用html元素点击事件常用方法小结
2017/02/10 Javascript
收藏AngularJS中最重要的核心功能
2017/07/09 Javascript
vue2.0组件之间传值、通信的多种方式(干货)
2018/02/10 Javascript
总结js函数相关知识点
2018/02/27 Javascript
详解vue 计算属性与方法跟侦听器区别(面试考点)
2018/04/23 Javascript
Nuxt.js之自动路由原理的实现方法
2018/11/21 Javascript
vue.js 打包时出现空白页和路径错误问题及解决方法
2019/06/26 Javascript
vue 自动化路由实现代码
2019/09/03 Javascript
微信小程序实现下拉加载更多商品
2020/12/29 Javascript
解决python xlrd无法读取excel文件的问题
2018/12/25 Python
Python多线程处理实例详解【单进程/多进程】
2019/01/30 Python
python实现两个一维列表合并成一个二维列表
2019/12/02 Python
如何将你的应用迁移到Python3的三个步骤
2019/12/22 Python
聊聊python中的循环遍历
2020/09/07 Python
小结Python的反射机制
2020/09/28 Python
Python基于locals返回作用域字典
2020/10/17 Python
Python接口自动化系列之unittest结合ddt的使用教程详解
2021/02/23 Python
2013年学期结束动员演讲稿
2014/01/07 职场文书
公司同意接收函
2014/01/13 职场文书
网吧消防安全制度
2014/01/28 职场文书
大学生毕业自我鉴定范文
2014/02/03 职场文书
美术社团活动总结
2014/06/27 职场文书
环境工程专业毕业生求职信
2014/09/30 职场文书
工作态度不端正检讨书
2014/10/04 职场文书
2014年图书管理员工作总结
2014/12/01 职场文书
在职人员跳槽求职信
2015/03/20 职场文书
专项资金申请报告
2015/05/15 职场文书
给朋友的赠语
2015/06/23 职场文书
新学期主题班会
2015/08/17 职场文书
mysql自增长id用完了该怎么办
2022/02/12 MySQL