python MySQLdb使用教程詳解
本文主要內(nèi)容python MySQLdb數(shù)據(jù)庫批量插入insert,更新update的:
1.python MySQLdb的使用,寫了一個(gè)基類讓其他的sqldb繼承這樣比較方便,數(shù)據(jù)庫的ip, port等信息使用json配置文件
2.常見的查找,批量插入更新

下面貼出基類代碼:
# _*_ coding:utf-8 _*_
import MySQLdb
import json
import codecs
# 這個(gè)自己改一下啊
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)
總結(jié)
以上所述是小編給大家介紹的python MySQLdb使用教程詳解,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
Python根據(jù)字典的值查詢出對(duì)應(yīng)的鍵的方法
這篇文章主要介紹了Python根據(jù)字典的值查詢出對(duì)應(yīng)的鍵的方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
Python 輸入一個(gè)數(shù)字判斷成績分?jǐn)?shù)等級(jí)的方法
今天小編就為大家分享一篇Python 輸入一個(gè)數(shù)字判斷成績分?jǐn)?shù)等級(jí)的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-11-11
使用jupyter notebook運(yùn)行python和R的步驟
這篇文章主要介紹了使用jupyter notebook運(yùn)行python和R的步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08
python對(duì)raw格式照片進(jìn)行降噪處理的方法詳解
要對(duì)RAW格式的照片進(jìn)行降噪,我們可以使用rawpy庫來讀取RAW圖像,并使用imageio庫將處理后的圖像保存為其他格式,如PNG或JPEG,本文將詳細(xì)給大家介紹python如何對(duì)raw格式照片進(jìn)行降噪處理,文中有詳細(xì)的代碼流程,需要的朋友可以參考下2023-05-05
python皮爾遜相關(guān)性數(shù)據(jù)分析分析及實(shí)例代碼
這篇文章主要為大家介紹了python皮爾遜相關(guān)性分析及實(shí)例代碼,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02
Python?中10進(jìn)制數(shù)與16進(jìn)制數(shù)相互轉(zhuǎn)換問題
這篇文章主要介紹了Python中10進(jìn)制數(shù)與16進(jìn)制數(shù)相互轉(zhuǎn)換,在Python中,我們可以使用內(nèi)置的hex()函數(shù)將10進(jìn)制數(shù)轉(zhuǎn)換為16進(jìn)制數(shù),需要的朋友可以參考下2023-05-05

