python MySQLdb使用教程详解
作者:FishBear_move_on 发布时间:2024-01-28 06:29:51
标签: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使用教程详解网站的支持!
来源:http://blog.csdn.net/haluoluo211/article/details/77721138


猜你喜欢
- access中可以将文本中的数据轻松导入表中,mysql中用起来没那么方便,其实起来也很简单。首先将数据记录按行处理好用特定的字符分开如:“
- 本文实例讲述了php获取客户端IP及URL的方法。分享给大家供大家参考,具体如下:function getonlineip(){//获取用户
- 很多时候学习是一种难者不会,会者不难的事情。下面的5个python技巧是性价比极高的知识点,一学就会,不难但是相当管用。使用交互模式使用py
- 显示有限的接口到外部当发布python第三方package时,并不希望代码中所有的函数或者class可以被外部import,在__init_
- 查询语句的优化是SQL效率优化的一个方式,可以通过优化sql语句来尽量使用已有的索引,避免全表扫描,从而提高查询效率。最近在对项目中的一些s
- 什么是DLL文件?DLL文件为动态链接库(英语: Dynamic-link library, 缩写为DLL)它是微软公司在微软视窗操作系统中
- 配置 thriftpython使用的包 thrift个人使用的python 编译器是pycharm community edition. 在
- 找了半天,以为numpy的where函数像matlab 的find函数一样好用,能够返回一个区间内的元素索引位置。结果没有。。(也可能是我没
- 前言本文主要给大家介绍的是关于PHP/ThinkPHP实现批量打包下载文件的相关内容,分享出来供大家参考学习,话不多说了,来一起看看详细的介
- Python3 基础语法编码默认情况下,Python 3 源码文件以 UTF-8 编码,所有字符串都是 unicode 字符串。当然你也可以
- 最近被告知,MySQL主从数据库的数据不一致,猜测备库在同步过程中出现了问题,于是,登上备库,使用 mysql> show slave
- 本文实例为大家分享了python手写均值滤波的具体代码,供大家参考,具体内容如下原理与卷积类似,设置一个n*n的滤波模板,滤波模板内的值累加
- 以下是详细步骤:1、查看磁盘空间情况:[root@localhost backup]# df -h文件系统 &n
- Golang浮点数比较和运算会出现误差。浮点数储存至内存中时,2的-1、-2……-n次方不能精确的表示小数部分,所以再把这个数从地址中取出来
- 1、使用 runefunc BenchmarkSubstr1(b *testing.B) {s := "bench基准测试,121
- 本文实例讲述了Go语言中的range用法。分享给大家供大家参考。具体如下:for 循环的 range 格式可以对 slice 或者 map
- Python由Guido Van Rossum发明于90年代初期,是目前最流行的编程语言之一,因其语法的清晰简洁我爱上了Python,其代码
- 效果知识点:css3画气球, 自定义属性运用,随机阵列, DOM元素操作,高级回调函数与参数复传,动态布局,鼠标事件,定时器运用,CSS3新
- vue element-ui动态面包屑导航,供大家参考,具体内容如下直接上代码一、template代码// 这是单独的组件<templ
- 前言在我们很多应用中会遇到有一种基于一系列时间的数据需要处理,通过时间的顺序可以将这些数据点连成线,再通过数据统计后可以做成多纬度的报表,也