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中操作mysql的pymysql模块详解
Sep 13 Python
Golang与python线程详解及简单实例
Apr 27 Python
[原创]教女朋友学Python(一)运行环境搭建
Nov 29 Python
Python+树莓派+YOLO打造一款人工智能照相机
Jan 02 Python
Python使用pandas处理CSV文件的实例讲解
Jun 22 Python
python实现Flappy Bird源码
Dec 24 Python
Python3.5内置模块之time与datetime模块用法实例分析
Apr 27 Python
Python任意字符串转16, 32, 64进制的方法
Jun 12 Python
python实现PID算法及测试的例子
Aug 08 Python
python实现单张图像拼接与批量图片拼接
Mar 23 Python
用Python实现定时备份Mongodb数据并上传到FTP服务器
Jan 27 Python
pd.DataFrame中的几种索引变换的实现
Jun 16 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中使用XML
2006/10/09 PHP
php桌面中心(一) 创建数据库
2007/03/11 PHP
PHP获取当前文件的父目录方法汇总
2016/07/21 PHP
PHP更安全的密码加密机制Bcrypt详解
2017/06/18 PHP
Cookie跨域问题解决方案代码示例
2020/11/24 PHP
分享一道笔试题[有n个直线最多可以把一个平面分成多少个部分]
2012/10/12 Javascript
jQuery中:focus选择器用法实例
2014/12/30 Javascript
javascript操作select元素实例分析
2015/03/27 Javascript
JavaScript变量的作用域全解析
2015/08/14 Javascript
下雪了 javascript实现雪花飞舞
2020/08/02 Javascript
全面解析标签页的切换方式
2016/08/21 Javascript
js原生跨域_用script标签的简单实现
2016/09/24 Javascript
jQuery获取table表中的td标签(实例讲解)
2017/07/28 jQuery
基于JavaScript实现淘宝商品广告效果
2017/08/10 Javascript
解决ie img标签内存泄漏的问题
2017/10/13 Javascript
vue-router源码之history类的浅析
2019/05/21 Javascript
Vue数据双向绑定底层实现原理
2019/11/22 Javascript
python字典get()方法用法分析
2015/04/17 Python
一道python走迷宫算法题
2018/01/22 Python
python中实现数组和列表读取一列的方法
2018/04/03 Python
解决PyCharm同目录下导入模块会报错的问题
2018/10/13 Python
python基于paramiko将文件上传到服务器代码实现
2019/07/08 Python
Python实现AI换脸功能
2020/04/10 Python
Python如何生成xml文件
2020/06/04 Python
如何使用Django Admin管理后台导入CSV
2020/11/06 Python
阿里健康大药房:阿里自营网上药店
2017/08/01 全球购物
英国最大的自有市场,比亚马逊便宜:Flubit
2019/03/19 全球购物
2014学习优秀共产党员先进事迹思想汇报
2014/09/14 职场文书
我的大学四年规划书范文2014
2014/09/26 职场文书
教师年度考核个人总结
2015/02/12 职场文书
综合素质评价个性发展自我评价
2015/03/06 职场文书
2015年六一儿童节活动方案
2015/05/05 职场文书
小学三年级数学教学反思
2016/02/16 职场文书
golang goroutine顺序输出方式
2021/04/29 Golang
CSS 新特性 contain控制页面的重绘与重排问题
2021/04/30 HTML / CSS
Nginx进程调度问题详解
2021/09/25 Servers