python MySQLdb使用教程詳解
本文主要內(nèi)容python MySQLdb數(shù)據(jù)庫批量插入insert,更新update的:
1.python MySQLdb的使用,寫了一個基類讓其他的sqldb繼承這樣比較方便,數(shù)據(jù)庫的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)
總結(jié)
以上所述是小編給大家介紹的python MySQLdb使用教程詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
使用Django2快速開發(fā)Web項目的詳細(xì)步驟
這篇文章主要介紹了使用Django2快速開發(fā)Web項目的詳細(xì)步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01Python 最強編輯器詳細(xì)使用指南(PyCharm )
這篇文章主要介紹了Python 最強編輯器詳細(xì)使用指南(PyCharm),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09python中的__init__ 、__new__、__call__小結(jié)
這篇文章主要介紹了python中的__init__ 、__new__、__call__小結(jié),需要的朋友可以參考下2014-04-04Python處理不同接口間參數(shù)依賴的方法總結(jié)
這篇文章主要為大家詳細(xì)介紹了如何使用Python編寫接口自動化測試,以有效地處理不同接口之間的參數(shù)依賴,并提供豐富的示例代碼,希望對大家有所幫助2024-01-01昨晚我用python幫隔壁小姐姐P證件照然后發(fā)現(xiàn)
大家好,我是Lex 喜歡欺負(fù)超人那個Lex 建議大家收藏哦,以后幫小姐姐P自拍,證件照,調(diào)尺寸,背景,摳圖,直接10行代碼搞定,瞬間高大上2021-08-08能讓你輕松的實現(xiàn)自然語言處理的5個Python庫
今天教大家如何你輕松的實現(xiàn)自然語言預(yù)處理,僅僅需要5個python庫,文中介紹的非常詳細(xì),對正在學(xué)習(xí)python的小伙伴們有很好的幫助,需要的朋友可以參考下2021-05-05利用Python第三方庫xlrd讀取Excel中數(shù)據(jù)實例代碼
python操作excel主要用到xlrd和xlwt這兩個庫,即xlrd是讀excel,xlwt是寫excel的庫,下面這篇文章主要給大家介紹了關(guān)于利用Python第三方庫xlrd讀取Excel中數(shù)據(jù)的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-07-07