本文實(shí)例講述了Python使用MYSQLDB實(shí)現(xiàn)從數(shù)據(jù)庫(kù)中導(dǎo)出XML文件的方法。分享給大家供大家參考。具體分析如下:
這里需要給前端以xml格式提供一些數(shù)據(jù),這些數(shù)據(jù)在目前的數(shù)據(jù)庫(kù)中已經(jīng)存在。
如果使用django返回xml數(shù)據(jù)的話,需要包裝下頭信息:
r.mimetype = "text/xml"
r['Content-Type'] = "application/xml"
另外,使用group by可以使用以下方式來(lái)查詢。
簡(jiǎn)單的舉個(gè)例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
# -*- 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() |
希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。