代码如下:
import os
import os.path
import sys
import MySQLdb
conn = MySQLdb.connect(host='10.100.1.95', user='leyuyin', passwd='leyuyin', port =3308, db='weather', charset='utf8')
cursor = conn.cursor()
count = cursor.execute('select distinct province from CITY_CODE')
print '总共有%s条记录' %count
command = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
command += "<dicts>\n"
result = cursor.fetchall();
for i in result:
cursor.execute("select code from CITY_CODE where province = '%s' and province = name" %i[0])
command += "<province code=\""
province = cursor.fetchone();
command += str(province[0])
command += "\" name=\""
command += i[0]
command += "\">"
command +="\n"
print "select distinct city from CITY_CODE where province = '%s' and city != province " %i[0]
count = cursor.execute("select distinct city from CITY_CODE where province = '%s' and city != province " %i[0])
if(count == 0):
count = cursor.execute("select distinct name from CITY_CODE where province = '%s' and name != province " %i[0])
for m in cursor.fetchall():
cursor.execute("select code from CITY_CODE where name = '%s' and city = '%s'" %(m[0],i[0]))
command += "<town code=\""
town = cursor.fetchone();
command += str(town[0])
command += "\" name=\""
command += m[0]
command += "\"/>"
command +="\n"
print '共有%s条记录' %count
cityresult=cursor.fetchall()
for n in cityresult:
print "select code from CITY_CODE where city = '%s' and city = name" %n[0]
citycount = cursor.execute("select code from CITY_CODE where city = '%s' and city = name" %n[0])
if(citycount >=0):
if(citycount == 0):
command += "<city code=\""
command += "\" name=\""
command += n[0]
command += "\">"
command +="\n"
else:
command += "<city code=\""
city = cursor.fetchone();
command += str(city[0])
command += "\" name=\""
command += n[0]
command += "\">"
command +="\n"
count = cursor.execute("select distinct name from CITY_CODE where city = '%s' and city != name" %n[0])
for m in cursor.fetchall():
cursor.execute("select code from CITY_CODE where name = '%s' and city = '%s'" %(m[0], n[0]))
command += "<town code=\""
town = cursor.fetchone();
command += str(town[0])
command += "\" name=\""
command += m[0]
command += "\"/>"
command +="\n"
command += "</city>"
command +="\n"
command += "</province>"
command +="\n"
command += "</dicts>"
command +="\n"
print command
file_object = open('city.xml', 'w')
file_object.writelines(command.encode('utf-8'))
file_object.close()
cursor.close()
conn.close()