• python连接sqllite处理xml成表


    track.py:

    import xml.etree.ElementTree as ET
    import sqlite3
    
    conn = sqlite3.connect('trackdb.sqlite')
    cur = conn.cursor()
    
    # Make some fresh tables using executescript()
    cur.executescript('''
    DROP TABLE IF EXISTS Artist;
    DROP TABLE IF EXISTS Album;
    DROP TABLE IF EXISTS Track;
    
    CREATE TABLE Artist (
        id  INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
        name    TEXT UNIQUE
    );
    
    CREATE TABLE Album (
        id  INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
        artist_id  INTEGER,
        title   TEXT UNIQUE
    );
    
    CREATE TABLE Track (
        id  INTEGER NOT NULL PRIMARY KEY 
            AUTOINCREMENT UNIQUE,
        title TEXT  UNIQUE,
        album_id  INTEGER,
        len INTEGER, rating INTEGER, count INTEGER
    );
    ''')
    
    
    # fname = input('Enter file name: ')
    # if ( len(fname) < 1 ) :
    fname = 'Library.xml'
    # <key>Track ID</key><integer>369</integer>
    # <key>Name</key><string>Another One Bites The Dust</string>
    # <key>Artist</key><string>Queen</string>
    def lookup(d, key):
        found = False
        for child in d:
            if found : return child.text
            if child.tag == 'key' and child.text == key :
                found = True
        return None
    
    stuff = ET.parse(fname)
    all = stuff.findall('dict/dict/dict')
    print('Dict count:', len(all))
    for entry in all:
        if ( lookup(entry, 'Track ID') is None ) : continue
    
        name = lookup(entry, 'Name')
        artist = lookup(entry, 'Artist')
        album = lookup(entry, 'Album')
        count = lookup(entry, 'Play Count')
        rating = lookup(entry, 'Rating')
        length = lookup(entry, 'Total Time')
    
        if name is None or artist is None or album is None : 
            continue
    
        print(name, artist, album, count, rating, length)
    
        cur.execute('''INSERT OR IGNORE INTO Artist (name) 
            VALUES ( ? )''', ( artist, ) )
        cur.execute('SELECT id FROM Artist WHERE name = ? ', (artist, ))
        artist_id = cur.fetchone()[0]
    
        cur.execute('''INSERT OR IGNORE INTO Album (title, artist_id) 
            VALUES ( ?, ? )''', ( album, artist_id ) )
        cur.execute('SELECT id FROM Album WHERE title = ? ', (album, ))
        album_id = cur.fetchone()[0]
    
        cur.execute('''INSERT OR REPLACE INTO Track
            (title, album_id, len, rating, count) 
            VALUES ( ?, ?, ?, ?, ? )''', 
            ( name, album_id, length, rating, count ) )
    
        conn.commit()

    xml: https://www.py4e.com/code3/tracks/Library.xml

  • 相关阅读:
    day54——Python 处理图片
    day53——Python 处理 Excel 数据
    day52——Python 处理附件
    day51——爬虫(一)
    大数据治理体系简谈
    redis环境的安装
    微服务体系操作日志如何记录?
    mysql数据库设计规范
    win系统下git代码批量克隆,批量更新
    java实现二维码登录功能
  • 原文地址:https://www.cnblogs.com/zhishaofei/p/16381416.html
Copyright © 2020-2023  润新知