简体   繁体   English

从PSQL数据库表生成XML文件的Python脚本

[英]Python script to generate XML file from PSQL database table

I am trying to generate XML file from PostgreSQL database table. 我正在尝试从PostgreSQL数据库表生成XML文件。 I was able to generate using below code but it is not formatted and displaying in single line. 我能够使用下面的代码生成,但未格式化并以单行显示。 While getting row from rows it displays complete file in single row. 从行中获取行时,它会在一行中显示完整的文件。 How can I fix this problem? 我该如何解决这个问题?

def tableToXML(message):
    conn = None
    try:
        conn=psycopg2.connect("dbname='DB' user='user' password='i123456'")
    except:
        print "I am unable to connect to the database."

    cur = conn.cursor()
    try:
        cur.execute("SELECT table_to_xml('usapp_sipconf', true, false, '')")
    except:
        print "I can't SELECT from sipconf"

    rows = cur.fetchall()
    with open('sipconf.xml', 'w') as f:
        for row in rows:
            print row
            f.write("%s" % (str(row)))
    if conn:
        conn.close()
    return True

I have generated XML file from PostgreSQL database table by making thses modification to pre-existing code. 通过对现有代码进行修改,我已经从PostgreSQL数据库表中生成了XML文件。

def tableToXML(tableName):
    conn       = None
    columnList = []
    fileName   = 'usappxml/'+tableName+'.xml'
    message    = '<'+tableName+'>\n'

    try:
        conn = psycopg2.connect("dbname='db' user='dbuser' password='123456'")
    except:
        print " ***  Can't able to connect database. *** "
        return False

    outfile = file(fileName, 'w')
    cursor  = conn.cursor()

    cursor.execute("SELECT column_name from information_schema.columns where table_name = '%s'" % tableName)
    columns = cursor.fetchall()

    for column in columns:
        columnList.append(column[0])

    cursor.execute("select * from  %s" % tableName)
    rows = cursor.fetchall()

    outfile.write('<?xml version="1.0" ?>\n')
    outfile.write(message)
    for row in rows:
        outfile.write('  <row>\n')
        for i in range(len(columnList)):
            outfile.write('    <%s>%s</%s>\n' % (columnList[i], row[i], columnList[i]))
             outfile.write('    <%s>%s</%s>\n' % (columnList[i], row[i], columnList[i]))
        outfile.write('  </row>\n')
     outfile.write(message)

    outfile.close()
    return True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM