使用Python对导MySQL数据表

2022年6月7日 13:41 by wst

python小技巧

今天写了个导出导入MySQL的代码,本来没想这么复杂。

尝试路径如下:

1. 想通过工具实现,无奈工具下载后连接不到库。

因为安全原因,设置库只能本机访问,那么就需要先访问服务器,然后连接库,不知为啥老是报超时,试了n遍也不行。

2. 用mysql自带的命令吧,但是搜了半天也没发现好用的。要么就是改库的安全设置,要么就是导出后,导入报错。放弃。

3.  实在不行,那我就自己写代码导,不用依赖任何工具了。只用python就好。

代码如下:

#!/usr/bin/env python

"""
FileName: migrate
Author: wst
Email: movingheart000@gmail.com
Date: 2022/6/7 12:08:51
Desc: 迁移数据库
"""

import pymysql
import logging
from logging.handlers import TimedRotatingFileHandler


MYSQL_CONFIG = {
    "formal": {
        "host": '127.0.0.1',
        "user": "root",
        "password": "11111111",
        "db": "t_whqj",
        "charset": "utf8",
    },
    "mongo_to_mysql": {
        "host": '127.0.0.1',
        "user": "root",
        "password": "11111111",
        "db": "whqj",
        "charset": "utf8",
    },
}


def init_log(log_name):
    logging.basicConfig(level=logging.INFO)
    # m 代表分钟,h 代表小时,d 代表天;backupCount 代表备份的天数
    console = TimedRotatingFileHandler("%s" % log_name, when='d', backupCount=10)
    console.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
    console.setFormatter(formatter)
    logging.root.addHandler(console)
    # 如果不想在命令行窗口输出,去掉下一行的注释
    # logging.root.handlers.pop(0)


def export_data(table, columns):
    """ 导出数据 """
    conn_wl = pymysql.connect(**MYSQL_CONFIG["formal"])
    cur_wl = conn_wl.cursor()

    conn = pymysql.connect(**MYSQL_CONFIG["mongo_to_mysql"])
    cur = conn.cursor()

    sql_wl = "select %(columns)s from %(table)s;" % {'columns': ",".join(columns), 'table': table}
    sql = """insert into %(table)s(%(columns)s) values(%(v)s);""" % {
        'columns': ",".join(columns), 'table': table, "v": ",".join(['%s' for _ in range(len(columns))])}

    res_wl = cur_wl.execute(sql_wl)
    size = 100
    rows = cur_wl.fetchmany(size)

    while rows:
        logging.info("The batch ...")
        cur.executemany(sql, rows)
        conn.commit()
        rows = cur_wl.fetchmany(size)

    cur.close()
    cur_wl.close()
    conn.close()
    conn_wl.close()


if __name__ == "__main__":
    init_log("mydata.log")
    logging.info("Start ...")

    # # 迁移运输工具表
    # columns = ('create_time', 'update_time', 'name', 'phone', 'note', 'state', 'vehicle_type_id', 'picture', 'id')
    # export_data("conveyance", columns)

    # # 迁移机器表
    # columns = ('id', 'platform', 'account', 'config', 'system', 'end_date', 'ip_inner', 'ip', 'create_time', 'note')
    # export_data("source_machine", columns)

    # # 迁移机器账号表
    # columns = ('id', 'user', 'password', 'create_time', 'note', 'ip_id')
    # export_data("source_machineaccount", columns)

    # 迁移域名表
    columns = ('id', 'domain', 'owner', 'record_number', 'create_time', 'note', 'ip_id', 'machine_id')
    export_data("source_domain", columns)

    logging.info("Done!")


版权声明:

本文刊载的所有内容,包括文字、图片以及网页版式设计等均为本人自主创作,访问者可将本文提供的内容或服务用于个人学习、研究或欣赏,以及其他非商业性或非盈利性用途,但同时应遵守著作权法及其他相关法律的规定,不得侵犯本文及作者的合法权利。除此以外,将本文任何内容或服务用于其他用途时,须征得本人的书面许可,并支付报酬。email: movingheart000@gmail.com, wx:wst_ccut


Comments(126) Add Your Comment

Hxlsgg
atorvastatin 40mg generic <a href="https://lipiws.top/">buy lipitor 40mg generic</a> cost atorvastatin 80mg
Tcfkjc
cipro 500mg generic - <a href="https://cipropro.top/">buy generic ciprofloxacin 1000mg</a> cost augmentin 625mg
Afnbmg
oral ciprofloxacin 500mg - <a href="https://metroagyl.top/">order ciprofloxacin 1000mg pill</a> buy augmentin 375mg generic
Equhij
buy ciplox no prescription - <a href="https://septrim.top/chloromycetin/">buy chloramphenicol medication</a> brand erythromycin 500mg
Hotbms
metronidazole pills - <a href="https://metroagyl.top/azithromycin/">buy azithromycin pill</a> zithromax price
Fpfvgt
where can i buy stromectol - <a href="https://keflexin.top/sumycin/">sumycin online order</a> buy sumycin 500mg for sale
Jqsezo
valacyclovir 1000mg for sale - <a href="https://gnantiviralp.com/">valacyclovir 500mg uk</a> zovirax cost
Irymax
buy ampicillin pills for sale <a href="https://ampiacil.top/amoxil500/">order amoxil online</a> order amoxicillin sale
Fvxjrm
metronidazole over the counter - <a href="https://metroagyl.top/azithromycin/">zithromax 500mg tablet</a> buy zithromax 500mg for sale
Eqyjgv
furosemide 40mg drug - <a href="https://antipathogenc.com/capoten/">captopril for sale</a> capoten over the counter
Okjyto
purchase glycomet online cheap - <a href="https://gnantiacidity.com/combivir/">lamivudine canada</a> lincocin 500mg generic
Xepksm
brand retrovir 300mg - <a href="https://canadiangnp.com/epivir/">epivir 100mg generic</a> purchase allopurinol pills
Jfuhmd
clozaril usa - <a href="https://genonlinep.com/amaryl/">order glimepiride 4mg</a> buy pepcid 40mg pills
Tgdinc
clomipramine uk - <a href="https://antdeponline.com/asendin/">oral asendin 50mg</a> buy doxepin paypal
Sexqth
quetiapine pill - <a href="https://gnkantdepres.com/eskalith/">buy eskalith tablets</a> eskalith ca
Aqvqdg
hydroxyzine 25mg tablet - <a href="https://antdepls.com/buspar/">buy buspar 5mg without prescription</a> amitriptyline 10mg ca
Wwkahw
purchase augmentin pills - <a href="https://atbioinfo.com/linezolid/">linezolid 600mg for sale</a> ciprofloxacin 500mg usa
Bdktzy
order amoxicillin sale - <a href="https://atbioxotc.com/erythromycin/">buy erythromycin online cheap</a> baycip without prescription
Gvydzh
zithromax medication - <a href="https://gncatbp.com/emetronidazole/">flagyl order</a> ciprofloxacin 500mg tablet
Xphbbw
buy cleocin pills - <a href="https://cadbiot.com/doxycycline/">monodox without prescription</a> chloromycetin cheap
Dgsnqg
stromectol generic - <a href="https://antibpl.com/szdoryx/">doxycycline sale</a> buy cefaclor 500mg sale
Ulgdpe
purchase albuterol - <a href="https://antxallergic.com/">ventolin 4mg over the counter</a> order theophylline sale
Wnervx
depo-medrol brand - <a href="https://ntallegpl.com/montelukast/">generic singulair 5mg</a> order generic azelastine 10ml
Pmhgzu
clarinex brand - <a href="https://rxtallerg.com/">buy desloratadine online</a> order albuterol online cheap
Majvcl
order glyburide without prescription - <a href="https://prodeprpl.com/">buy glyburide 2.5mg online cheap</a> forxiga 10mg canada
Qaoydw
cheap prandin - <a href="https://depressinfo.com/">order repaglinide 2mg generic</a> buy generic jardiance 25mg
Hkjoyi
rybelsus 14mg usa - <a href="https://infodeppl.com/glucovance5/">purchase glucovance online</a> buy desmopressin online cheap
Osdgms
purchase lamisil - <a href="https://treatfungusx.com/">lamisil pills</a> buy grifulvin v cheap
Ususzd
order famciclovir 250mg online - <a href="https://amvinherpes.com/">famciclovir 250mg canada</a> buy valaciclovir 500mg without prescription
Xnbzhj
buy nizoral 200 mg online - <a href="https://antifungusrp.com/butenafinecream/">buy butenafine generic</a> itraconazole 100 mg pills
Nabofi
lanoxin 250 mg uk - <a href="https://blpressureok.com/avalidemed/">buy generic avapro 300mg</a> buy generic lasix diuretic
Frcfhp
metoprolol for sale online - <a href="https://bloodpresspl.com/propranolol/">inderal 10mg generic</a> nifedipine 30mg oral
Fotsam
order hydrochlorothiazide 25mg generic - <a href="https://norvapril.com/amlodipine/">buy amlodipine sale</a> zebeta 10mg uk
Tuaazr
nitroglycerin medication - <a href="https://nitroproxl.com/">nitroglycerin pill</a> order diovan 80mg generic
Ezmnki
zocor tread - <a href="https://canescholest.com/">simvastatin later</a> atorvastatin tremendous
Qfpuqk
rosuvastatin online player - <a href="https://antcholesterol.com/">rosuvastatin online doctor</a> caduet goodness
Stpiyc
viagra professional stretch - <a href="https://edsildps.com/levitraoraljelly/">levitra oral jelly ice</a> levitra oral jelly sit
Hycmqd
dapoxetine sleep - <a href="https://promedprili.com/fildena/">fildena powerful</a> cialis with dapoxetine heel
Nspwai
cenforce wed - <a href="https://xcenforcem.com/">cenforce online chew</a> brand viagra pills chance
Wexqex
brand cialis traveller - <a href="https://probrandtad.com/penisole/">penisole peril</a> penisole title
Ryapld
brand cialis heap - <a href="https://probrandtad.com/alprostadilonline/">alprostadil evil</a> penisole gang
Secytb
cialis soft tabs pills alone - <a href="https://supervalip.com/viagraoraljelly/">viagra oral jelly online prison</a> viagra oral jelly stretch
Rwkrdy
cialis soft tabs pills watch - <a href="https://supervalip.com/cialissuperactive/">cialis super active staff</a>1 viagra oral jelly online unexpected
Kvjoww
priligy bid - <a href="https://promedprili.com/suhagra/">suhagra frog</a> cialis with dapoxetine various
Wdydzo
cenforce online dusty - <a href="https://xcenforcem.com/tadalissxtadalafil/">tadalis pills pound</a> brand viagra online although
Azfixq
asthma medication blossom - <a href="https://bsasthmaps.com/">asthma medication log</a> asthma treatment flicker
Wmkvzx
acne medication halfway - <a href="https://placnemedx.com/">acne treatment weird</a> acne medication grasp
Wtsgft
prostatitis pills ordinary - <a href="https://xprosttreat.com/">prostatitis pills doorway</a> pills for treat prostatitis murder
Xhvyte
treatment for uti debate - <a href="https://amenahealthp.com/">uti medication range</a> uti medication attract
Lpksvh
loratadine non - <a href="https://clatadine.top/">loratadine medication scramble</a> loratadine medication performance
Fpqdfa
valtrex lawn - <a href="https://gnantiviralp.com/">valtrex when</a> valtrex pills learn
Sacexv
dapoxetine how - <a href="https://prilixgn.top/">priligy cease</a> dapoxetine confidence
Bgsjcq
claritin pills tree - <a href="https://clatadine.top/">loratadine medication hurt</a> loratadine together
Aqzklf
ascorbic acid empty - <a href="https://ascxacid.com/">ascorbic acid tray</a> ascorbic acid startle
Whmhbn
promethazine troll - <a href="https://prohnrg.com/">promethazine cling</a> promethazine when
Kndqoi
biaxin pills pale - <a href="https://gastropls.com/">clarithromycin dig</a> cytotec saturday
Wwztnt
fludrocortisone pills pace - <a href="https://gastroplusp.com/propantoprazole/">protonix pills nanny</a> prevacid central
Ncjxaj
order generic rabeprazole - <a href="https://gastrointesl.com/">order rabeprazole online</a> buy domperidone 10mg generic
Kcicrt
dulcolax 5 mg for sale - <a href="https://gastroinfop.com/oxybutynin/">order oxytrol generic</a> brand liv52
Kffhsx
buy hydroquinone generic - <a href="https://danaterone.shop/">hydroquinone where to buy</a> duphaston 10 mg canada
Qducbu
bactrim 960mg for sale - <a href="https://tobmycin.com/">tobrex 5mg cheap</a> buy generic tobramycin 10mg
Mryunw
fulvicin 250mg pills - <a href="https://dipyrilx.com/">buy dipyridamole generic</a> lopid 300 mg us
Dherhp
dapagliflozin 10 mg tablet - <a href="https://precarbos.com/">acarbose over the counter</a> acarbose online buy
Asuqeq
buy dramamine 50mg - <a href="https://prasilx.com/">prasugrel where to buy</a> buy generic actonel for sale
Ggmrvh
enalapril 10mg pill - <a href="https://doxapisin.com/">buy doxazosin 2mg generic</a> zovirax order
Fbjldr
buy monograph 600 mg - <a href="https://etodograph.com/">order generic monograph</a> cilostazol cheap
Snnmlq
oral feldene - <a href="https://rivastilons.com/">buy rivastigmine</a> buy cheap rivastigmine
Djmhbj
purchase hydrea online - <a href="https://hydroydrinfo.com/pentoxifylline/">pentoxifylline brand</a> buy cheap generic robaxin
Anbdss
divalproex tablet - <a href="https://adepamox.com/acetazolamide/">purchase diamox online cheap</a> buy topiramate pills
Bseyrk
norpace for sale - <a href="https://anorpica.com/lamotrigine/">lamotrigine price</a> order thorazine 100mg without prescription
Gauwcf
aldactone tablet - <a href="https://aldantinep.com/dipyridamole/">buy dipyridamole for sale</a> brand revia
Wqhils
cyclophosphamide medication - <a href="https://cycloxalp.com/trimetazidine/">trimetazidine online</a> order vastarel without prescription
Ofjkio
order cyclobenzaprine 15mg sale - <a href="https://abflequine.com/prasugrel/">prasugrel 10mg without prescription</a> order generic enalapril
Loaofq
buy ondansetron online - <a href="https://azofarininfo.com/oxybutynin/">oxytrol without prescription</a> order ropinirole 2mg
Mizkjk
buy generic ascorbic acid 500mg - <a href="https://mdacidinfo.com/isosorbidedinitrate/">buy isordil</a> cost prochlorperazine
Dgxpjc
where can i purchase durex gel - <a href="https://xalaplinfo.com/latanoprosteyedrops/">where can i buy zovirax</a> xalatan online order
Azyxbw
buy minoxidil no prescription - <a href="https://mdacidinfo.com/dutasteride/">dutas without prescription</a> propecia us
Xulpgq
arava 20mg cheap - <a href="https://infohealthybones.com/calciumcarbonate/">buy calcium carbonate generic</a> cheap cartidin pills
Odccxs
buy cheap generic verapamil - <a href="https://infoheartdisea.com/">calan 240mg generic</a> tenoretic sale
Ldxsvi
buy atenolol pill - <a href="https://heartmedinfox.com/sotalol/">buy betapace online cheap</a> carvedilol uk
Wabmhr
generic gasex - <a href="https://herbalinfomez.com/ashwagandha/">cheap ashwagandha pill</a> buy diabecon sale
Hqicel
buy atorlip medication - <a href="https://infoxheartmed.com/enalapril/">where to buy enalapril without a prescription</a> buy nebivolol 20mg online cheap
Oyvgzb
lasuna price - <a href="https://infoherbalmz.com/">buy lasuna without a prescription</a> himcolin without prescription
Yfxzsc
where to buy noroxin without a prescription - <a href="https://gmenshth.com/flutamide/">buy flutamide tablets</a> buy confido without a prescription
Zsydcj
buy generic finasteride - <a href="https://finmenura.com/alfuzosin/">buy uroxatral 10 mg pills</a> buy generic alfuzosin 10 mg
Awuknr
terazosin for sale - <a href="https://hymenmax.com/tamsulosin/">where to buy tamsulosin without a prescription</a> buy dapoxetine 60mg
Gqtyrj
buy speman without a prescription - <a href="https://spmensht.com/himplasia/">himplasia order</a> finasteride usa
Rzaqbb
buy trileptal 600mg for sale - <a href="https://trileoxine.com/">order oxcarbazepine 600mg online cheap</a> order synthroid 150mcg generic
Cpgscv
imusporin usa - <a href="https://asimusxate.com/gloperba/">colchicine pills</a> cost colchicine
Vfeinw
where can i buy lactulose - <a href="https://duphalinfo.com/">purchase lactulose without prescription</a> how to buy betahistine
Stdpaj
buy calcort pills - <a href="https://lazacort.com/">buy generic deflazacort</a> buy brimonidine no prescription
Advtkl
generic besifloxacin - <a href="https://besifxcist.com/">besifloxacin for sale</a> cheap sildamax for sale
Ivucux
neurontin 100mg drug - <a href="https://aneutrin.com/ibuprofen/">generic motrin</a> buy sulfasalazine 500 mg generic
Gucjjn
cost benemid 500 mg - <a href="https://bendoltol.com/">order generic benemid 500mg</a> where to buy carbamazepine without a prescription
Ktxwvs
celebrex 100mg cheap - <a href="https://celespas.com/">buy generic celecoxib for sale</a> indomethacin cost
Skcyyg
buy mebeverine pills - <a href="https://coloxia.com/">mebeverine 135 mg uk</a> buy pletal pills for sale
Sobutt
buy voltaren 50mg generic - <a href="https://dicloltarin.com/">diclofenac 50mg for sale</a> how to get aspirin without a prescription
Wmyfql
order rumalaya for sale - <a href="https://rumaxtol.com/amitriptyline/">endep 10mg us</a> elavil 10mg ca
Jbltyl
how to get pyridostigmine without a prescription - <a href="https://mestonsx.com/azathioprine/">azathioprine usa</a> imuran 25mg pill
Sjhvfy
cheap voveran pill - <a href="https://vovetosa.com/">buy cheap voveran</a> nimodipine price
Blxtup
order baclofen - <a href="https://baclion.com/">ozobax online</a> buy feldene for sale
Fgqlux
buy meloxicam without a prescription - <a href="https://meloxiptan.com/rtrizatriptan/">ketorolac cost</a> how to get ketorolac without a prescription
Nurjsx
buy periactin 4 mg generic - <a href="https://periheptadn.com/aszanaflex/">order tizanidine sale</a> buy tizanidine 2mg pill
Rtvrvm
purchase artane without prescription - <a href="https://voltapll.com/diclofenacgel/">order voltaren gel sale</a> order emulgel online
Vfsouz
order omnicef sale - <a href="https://omnixcin.com/aminocycline/"></a> cleocin generic
Kkxdzn
accutane pills - <a href="https://aisotane.com/asdeltasone/">order deltasone 5mg online cheap</a> deltasone 5mg cost
Ydtzwh
buy deltasone 10mg for sale - <a href="https://apreplson.com/prednisolone/">omnacortil canada</a> order zovirax generic
Nviblo
buy generic acticin online - <a href="https://actizacs.com/asbenzac/">order benzac cream</a> order retin cream for sale
Oazpew
cheap betnovate - <a href="https://betnoson.com/">order betamethasone</a> monobenzone oral
Jbzhrf
buy flagyl 400mg pill - <a href="https://cenforcevs.com/">order cenforce pill</a> how to buy cenforce
Muqnlj
oral augmentin 375mg - <a href="https://alevonted.com/">synthroid 100mcg ca</a> buy levothroid without prescription
Txhegv
cleocin 300mg without prescription - <a href="https://clinycinpl.com/">buy generic clindamycin for sale</a> order indomethacin sale
Blntsr
order losartan 50mg pill - <a href="https://cozartan.com/">cozaar online buy</a> oral cephalexin
Gbpfci
crotamiton where to buy - <a href="https://aeuracream.com/">order crotamiton cream</a> purchase aczone generic
Xnmocp
provigil usa - <a href="https://sleepagil.com/">buy modafinil 100mg generic</a> buy meloset 3 mg online
Gdnqel
buy zyban online - <a href="https://bupropsl.com/shuddhaguggulu/">buy shuddha guggulu for sale</a> cheap shuddha guggulu pills
Mfjdai
xeloda 500 mg uk - <a href="https://xelocap.com/naproxen/">order naprosyn 500mg for sale</a> danazol 100 mg cheap
Ilbndi
purchase progesterone sale - <a href="https://apromid.com/">progesterone 100mg drug</a> brand clomiphene
Cuuajy
norethindrone 5mg cheap - <a href="https://norethgep.com/bimatoprost/">purchase lumigan online cheap</a> buy cheap generic yasmin
Ffgrlz
order fosamax online cheap - <a href="https://pilaxmax.com/">cheap fosamax</a> buy medroxyprogesterone 5mg online
Vggoyg
buy dostinex sale - <a href="https://adostilin.com/">buy dostinex no prescription</a> buy alesse generic
Dtqdex
buy yasmin - <a href="https://festrolp.com/letrozole/">buy letrozole generic</a> cost arimidex 1 mg
Voguen
バイアグラ処方 - <a href="https://jpedpharm.com/">バイアグラ通販で買えますか</a> シアリス 値段
Qgcgzv
プレドニン通販 安全 - <a href="https://jpaonlinep.com/jamoxicillin/">アモキシル通販おすすめ</a> ジスロマック通販で買えますか
Svvzdl
プレドニン 市販 おすすめ - <a href="https://jpanfarap.com/jpadoxycycline/">ドキシサイクリンの飲み方と効果</a> イソトレチノイン通販
Vpgqqv
eriacta sneak - <a href="https://eriagra.com/szenegrag/">zenegra online anxious</a> forzest city