Python使用MYSQLDB实现从数据库中导出XML文件的方法

WBOY
Release: 2016-06-10 15:12:47
Original
1406 people have browsed it

本文实例讲述了Python使用MYSQLDB实现从数据库中导出XML文件的方法。分享给大家供大家参考。具体分析如下:

这里需要给前端以xml格式提供一些数据,这些数据在目前的数据库中已经存在。

如果使用django返回xml数据的话,需要包装下头信息:

复制代码 代码如下:
r = HttpResponse(str_xml)
r.mimetype = "text/xml"
r['Content-Type'] = "application/xml"
另外,使用group by可以使用以下方式来查询。
复制代码 代码如下:
objs = Fish.objects.raw("SELECT  id, almanac_name, style , almanac_code,almanac_description FROM ppy_fish WHERE almanac_name != ''  GROUP BY almanac_code")

简单的举个例子:

# -*- coding: utf-8 -*-
from xml.dom import minidom
import MySQLdb
conn = MySQLdb.connect(host='localhost',user='root',passwd='xxx',db='my_xml',charset="utf8")
cursor = conn.cursor()
cursor.execute('select id, name, style, description, family from ppy_fish')
res_list = cursor.fetchall()
print len(res_list)
doc = minidom.Document()
root = doc.createElement("data")
doc.appendChild(root)
ATTRIBUTE = {"n":1, "d":3}
for res in res_list:
  node = doc.createElement(res[2])
  for i in ATTRIBUTE:
    id_node = doc.createElement("%s" % i)
    data = doc.createTextNode("%s" % res[ATTRIBUTE[i]])
    id_node.appendChild(data)
    node.appendChild(id_node)
  root.appendChild(node)
str_xml = doc.toxml("utf-8")
f = open('fish.xml', 'w')
f.write(str_xml)
f.close()
cursor.close()
conn.close()
Copy after login

希望本文所述对大家的Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template