· 8 years ago · Jan 22, 2018, 09:26 AM
1#!/usr/bin/python
2
3import MySQLdb
4import xml.etree.ElementTree as ET
5
6try:
7 db = MySQLdb.connect(host="localhost", user="root", passwd="toor", db="myDB")
8
9 cursor = db.cursor()
10
11 # create query
12 tree = ET.parse('data.xml')
13 root = tree.getroot()
14 table_name = root.attrib['name']
15
16 print "table_name =>", table_name
17 columns = ''
18 for child in root:
19 field_name = child.attrib['name']
20 field_type = child.attrib['type']
21 columns += field_name + ' ' + field_type + ','
22 columns = columns[:-1]
23 print "columns =>", columns
24 query = "CREATE TABLE IF NOT EXISTS" + ' ' + table_name + '(' + columns + ')'
25 print "query =>", query
26 cursor.execute(query)
27
28 db.commit()
29
30except Exception as e:
31 print(e)