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')
genre = lookup(entry, 'Genre')
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 or genre is None:
continue
print(name, artist, album, genre, 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 IGNORE INTO Genre (name)
VALUES ( ? )''', (genre,))
cur.execute('SELECT id FROM Genre WHERE name = ? ', (genre,))
genre_id = cur.fetchone()[0]
cur.execute('''INSERT OR REPLACE INTO Track
(title, album_id, genre_id, len, rating, count)
VALUES ( ?, ?, ?, ?, ?, ? )''',
(name, album_id, genre_id, length, rating, count))
cur.execute('SELECT id FROM Artist WHERE name = ? ', (artist,))
artist_id = cur.fetchone()[0]
这一段看不明白起什么作用,作用机制是?
第一个是执行cur对象的函数(至于起什么作用,应查看函数的定义),第二个是复制语句。
上面一个是python查询数据库的操作,下面返回Artist表中id的值