python mysqldb insert_python MySQLdb使用教程详解
本文主要内容python MySQLdb数据库批量插入insert,更新update的:
1.python MySQLdb的使用,写了一个基类让其他的sqldb继承这样比较方便,数据库的ip, port等信息使用json配置文件
2.常见的查找,批量插入更新
下面贴出基类代码:
# _*_ 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 mysqldb insert_python MySQLdb使用教程详解相关推荐
- windows上安装Anaconda和python的教程详解
一提到数字图像处理编程,可能大多数人就会想到matlab,但matlab也有自身的缺点: 1.不开源,价格贵 2.软件容量大.一般3G以上,高版本甚至达5G以上. 3.只能做研究,不易转化成软件. 因 ...
- python安装教程windows-windows上安装Anaconda和python的教程详解
一提到数字图像处理编程,可能大多数人就会想到matlab,但matlab也有自身的缺点: 1.不开源,价格贵 2.软件容量大.一般3G以上,高版本甚至达5G以上. 3.只能做研究,不易转化成软件. 因 ...
- python安装方法3.8.2_Linux安装Python3.8.1的教程详解
本例以Linux上安装Pyhton3.8版本为例进行说明 1.依赖包安装 yum -y install zlib-devel bzip2-devel openssl-devel ncurses-dev ...
- pycharm导入python环境是空的_PyCharm导入python项目并配置虚拟环境的教程详解
PyCharm导入python项目并配置虚拟环境的教程详解 进入PyCharm后,点击File→Open,然后在弹窗中选择需要导入项目的文件夹: 打开了python项目后,需要配置该项目对应的pyth ...
- python入门教程pdf-Python入门教程详解.pdf
您所在位置:网站首页 > 海量文档  > 计算机 > Python Python入门教程详解.pdf132页 本文档一 ...
- python编译安装详解_linux 编译安装python3.6的教程详解
不要下载 " XZ compressed source tarball " ,目前 python3.6 最新版压缩包名字是:Python-3.6.7.tgz. 把下载的压缩包随便放 ...
- 在anaconda安装python命令_windows上安装Anaconda和python的教程详解
一提到数字图像处理编程,可能大多数人就会想到matlab,但matlab也有自身的缺点: 1.不开源,价格贵 2.软件容量大.一般3G以上,高版本甚至达5G以上. 3.只能做研究,不易转化成软件. 因 ...
- 检查python是否安装成功的命令是_Python 中的pygame安装与配置教程详解
安装软件环境及版本说明 OS: Win10 x 64 专业版 Python: 2.7 IDE: PyCharm Community 2018 1. 安装python 1)下载并安装python pyt ...
- Python爬虫教程-Python爬取股票数据过程详解
这篇文章主要介绍了基于Python爬取股票数据过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 基本环境配置 python 3.6 pycha ...
最新文章
- 在Scrapy中使用Chrome中的cookie
- window.open详解
- Oracle误删除数据和表的恢复办法包括truncate
- Python调用MongoDB使用心得
- Shell、内外部命令——Linux基本命令(2)
- Java中Map类型数据使用LinkedHashMap保留数据的插入顺序
- mysql 存储过程中limit
- linux java no x11_在linux下运行javaMail程序报No X11 DISPLAY variable was...
- 都是写需求,高手和菜鸟为何差别这么大?
- 自动化代码部署、代码回滚、命令执行软件之capistrano
- instanceof 和 构造函数
- SpringBoot注册组件之@Configuration@Bean注解作用及注意点
- php创建游戏房间思路,用Swoole来写个联机对战游戏呀!(八)创建游戏房间
- 方舟手游机服务器修改,方舟生存进化私服怎么设置 方舟手游私服设置教程
- 微信公众号模板消息(带流程图)
- C++struct里定义函数
- facebook登陆,如何邀请玩家成为测试人员
- 解决关于pycharm启动时持续Updating Indices的问题
- html可识别的字体,7款有用的工具来识别字体
- hook(2)Activity启动流程,安卓开发实战
热门文章
- server2003 IIS6.0 网站不可用
- 25-限制容器对内存的使用
- Netty 的基本简单实例【服务端-客户端通信】
- 神经网络----笔记(1)
- python基础之-数据类型
- Android 网络协议
- Eclipse 调试器
- 大数据_Flink_Java版_数据处理_流处理API_Transform(5)_union合流---Flink工作笔记0034
- C++_类和对象_对象特性_This指针的用途_用来解决名称冲突_*this实现链式编程---C++语言工作笔记049
- ActiveMq工作笔记001---Windows10下安装ActiveMq