Skip to content

Instantly share code, notes, and snippets.

@xenji
Created February 27, 2012 06:51
Show Gist options
  • Save xenji/1922020 to your computer and use it in GitHub Desktop.
Save xenji/1922020 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
def main():
import MySQLdb
conn = MySQLdb.connect (host="localhost", user="root", passwd="", db="crm")
cursor = conn.cursor ()
cursor.execute ("SELECT usf_id, usf_name FROM adm_user_fields")
aNameRows = cursor.fetchall()
kvMapNames = {}
for aNameRow in aNameRows:
kvMapNames[aNameRow[0]] = aNameRow[1]
headline = ",".join(kvMapNames.values()) + "\n"
cursor.execute("SELECT DISTINCT usd_usr_id FROM adm_user_data")
aUserData = cursor.fetchall()
aCSVRows = []
for row in aUserData:
cursor.execute("SELECT * FROM adm_user_data WHERE usd_usr_id=%d ORDER BY usd_usf_id" % row[0])
aData = cursor.fetchall()
aDataPresent = {}
for urow in aData:
print urow
aDataPresent[urow[2]] = urow[3]
for missingKey in [k for k in kvMapNames.keys() if k not in aDataPresent.keys()]:
aDataPresent[missingKey] = ""
aCSVRows.append(",".join(aDataPresent.values()) + "\n")
print headline
print "".join(aCSVRows)
f = open ("out.csv", "w")
f.write(headline)
f.write("".join(aCSVRows))
f.close()
if __name__ == '__main__': main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment