Python脚本连接数据库读取特定字段保存在文件中
从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