This is a simple function that takes records exported to XML from SQL Server or Access and imports them into MySQL.
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | ##
## XMLPush
##
## A small utility to move XML as exported from SQL Server or MS Access to a
## mySQL table.
##
## Not too fancy, but gets the job done. As with all recipes, season to taste
## depending on your needs.
##
## Albert L. Perrien II
## 08 March 2011
## aperrien@razodisk.com
##
import re
from lxml import etree
import MySQLdb
def XMLPush(datafile,server,dbuser,password,dbname,table)
def quote(text):
return "'" + text + "'"
def doublequote(text):
return '"' + text + '"'
connection = MySQLdb.connectionect (host = server,
user = dbuser,
passwd = password,
db = dbname)
cursor = connection.cursor()
tree = etree.parse(datafile)
root = tree.getroot()
# Parse out data from XML
data = []
for child in root:
datarow = {}
for leaf in child:
datarow[leaf.tag] = leaf.text
data.append(datarow)
# Push data to DB
statements = []
for row in data:
columns = []
values = []
for item in row:
# Reformatting data to mySQL formats
columns.append(item.replace(" ",""))
temp = row[item]
values.append(quote(temp.replace("'","")))
# Push data to table
statement = "INSERT INTO " + table + " (" + ",".join(columns) + ") VALUES (" + \
",".join(values) + ")"
statements.append(statement)
for statement in statements:
cursor.execute(statement)
connection.commit()
connection.close()
XMLPush("MainTable.xml","mySQL-Server","mySQL-User","mySQL-Password","DB_Name","Table")
|
I wrote this to move a bunch of records from an Access DB and SQL Server to MySQL when I couldn't find a method of importing between them directly, the only thing I could get from the SQL Server being a series of static XML dumps, due to regulatory issues. Let me know what you think!