码迷,mamicode.com
首页 > 数据库 > 详细

Python脚本连接数据库读取特定字段保存在文件中

时间:2017-12-04 16:44:48      阅读:438      评论:0      收藏:0      [点我收藏+]

标签:can   bre   sys   coding   argv   nis   ica   pre   mysql   

从Script表中取出Description字段作为文件名,并按协议将脚本归位相同的文件夹,取TestScript字段的内容写入文件

import MySQLdb
import sys
import os
from lxml import etree

IP=sys.argv[1]
#IP="10.0.20.252"
DIR="ScriptsDir"
try:
    print "connnect to database...."
    db=MySQLdb.connect(IP,"root","Free-Wi11","acheron_db")
except Exception as e:
    print e.message
    print "Can‘t connect to " + IP
    exit(1)

print "Done...."
print "Ready to read data from DataBase......"
db_cursor=db.cursor()

sql="select Description,TestScript from Script where Class=‘System‘"
db_cursor.execute(sql)
content=db_cursor.fetchall()
if os.path.exists(DIR):
   os.system("RD /S /Q " + DIR)
os.system("mkdir " + DIR)
for item in content:
    file_name=item[0]
    if len(file_name)==0:
        print item
        continue

    directory=item[0].split(".")[0]
    if len(directory)==0:
        print item
        continue
    if not os.path.exists(DIR+"\\"+directory):
        os.system("mkdir " + DIR + "\\"+directory)
    try:
        f=open(DIR+"\\"+directory+"\\"+file_name+".xml","w")
        root=etree.fromstring(item[1])
        f.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
        f.write(etree.tostring(root))
        f.close()
    except Exception as e:
        print e.message
        print "Failed,please retry...."
        break;
print "See Scripts data file in ‘" + DIR + ""
print "Done"

执行结果:

技术分享图片

从10.0.10.33上的mybatis数据库中将user表中的数据取出并存到本地user.txt文件夹下

看下user表:

技术分享图片

import MySQLdb

#IP=sys.argv[1]
IP="10.0.10.33"
FileName="user.txt"
try:
    print "connnect to database...."
    db=MySQLdb.connect(IP,"root","123456","mybatis")
except Exception as e:
    print e.message
    print "Can‘t connect to " + IP
    exit(1)

print "Done...."
print "Ready to read data from DataBase......"
db_cursor=db.cursor()
sql="select * from users"
db_cursor.execute(sql)
content=db_cursor.fetchall()
f=open(FileName,"w")
for item in content:
    try:
        # root=etree.fromstring(item[1])
        f.write("id: " + str(item[0]) +" name: " + item[1] + " age:" + str(item[2]))
        f.write("\r")
    except Exception as e:
        print e.message
        print "Failed,please retry......"
        break
f.close()
print "See user list in ‘" + FileName + ""
print "Done"

执行结果:

C:\Python27\python.exe G:/web2py/web2py_win/web2py/applications/pythonMySQLdb/pythonMySQL.py
connnect to database....
Done....
Ready to read data from DataBase......
See user list in user.txt
Done

Process finished with exit code 0

技术分享图片

Python脚本连接数据库读取特定字段保存在文件中

标签:can   bre   sys   coding   argv   nis   ica   pre   mysql   

原文地址:http://www.cnblogs.com/fangpengchengbupter/p/7977489.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!