Python uses MySQLdb to implement methods for exporting XML files from a database

Source: Internet
Author: User
This example describes how Python uses MySQLdb to implement exporting an XML file from a database. Share to everyone for your reference. The specific analysis is as follows:

Here you need to provide some data to the front end in XML format, which already exists in the current database.

If you use Django to return XML data, you need to wrap the head information:
Copy the Code code as follows:

R = HttpResponse (str_xml)
R.mimetype = "Text/xml"
r[' content-type '] = "Application/xml"


In addition, using group by can be queried using the following methods.
Copy CodeThe code is as follows:

OBJS = Fish.objects.raw ("Select ID, almanac_name, style, almanac_code,almanac_description from Ppy_fish WHERE almanac_na Me! = ' GROUP by Almanac_code ')

For a simple example:

#-*-Coding:utf-8-*-from xml.dom import minidomimport mysqldbconn = 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 ()

Hopefully this article will help you with Python programming.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.