2016-03-03 85 views
0

比方說,我有這樣的矩陣:Python和sqlite3的:插入基質爲表

[[[u'artist1'], [u'song1']], [[u'artist2'], [u'song2']], [[u'artist3'], [u'song3']]] 

我不知道我怎樣才能將它插入SQL表,所以它看起來是這樣的:

ID | ARTIST |SONG 
----------------- 
1 | artist1 | song1 
2 | artist2 | song2 
3 | artist3 | song3 

我有大約100萬的藝術家和100萬首歌曲,我不得不插入所以這只是一個例子:P

在此先感謝!

的源代碼:

import sqlite3 
import numpy as np 
print('Opening SQL Database') 
sql = sqlite3.connect('mblite_post.db') 
cur = sql.cursor() 
cursor=cur.execute("SELECT entity0 from r_artist_release LIMIT 500000000000000 ") 
result_author = [row[0] for row in cur.fetchall()] 

cursor=cur.execute("SELECT entity1 from r_artist_release LIMIT 500000000000000 ") 
result_song = [row[0] for row in cur.fetchall()] 


artistlist=[] 
for x in result_author: 
    y=cur.execute("SELECT name FROM artist_name where id='%s'" % x) 
    artistname=[row[0] for row in cur.fetchall()] 
    artistlist.append(artistname) 
songlist=[] 
for y in result_song: 
    z=cur.execute("SELECT name FROM release_name where id='%s'" % y) 
    songname=[row[0] for row in cur.fetchall()] 
    songlist.append(songname) 



matrix2 = [[artistlist[i], songlist[i]] for i in range(len(artistlist))] 

print(len(matrix2)) 
sql2 = sqlite3.connect('itaidb.db') 
cur2 = sql2.cursor() 
cur2.execute('CREATE TABLE IF NOT EXISTS main (artist TEXT,song TEXT)') 


for i, v in enumerate(matrix2): 
    cur2.execute('INSERT INTO main VALUES (?,?)', (v[0][0], v[1][0])) 
    sql2.commit() 



# 
# 
# for ton in songlist: 
#  cur2.execute("UPDATE main SET (song) values (?) WHERE id='%r'", [''.join(ton)] % integer) 
#  sql2.commit() 
#  integer=integer+1 
# 
sql2.close() 
sql.close() 

# artistname=[] 
# for x in author: 
#  y=cur.execute("SELECT name FROM artist_name where id='%s'" % x) 
#  artistname=artistname.append(list(y.fetchall())) 
# 
# print artistname 

回答

0

我建議你創建你這樣的名單:

yourlist = [(artistlist[i], songlist[i]) for i, v in enumerate(artistlist)] 

然後你可以使用一個for循環來執行INSERT聲明:

for i, v in enumerate(yourlist, start=1): 
    cursor.execute('INSERT INTO yourtable VALUES (?,?,?)', (i, v[0], v[1])) 

之後不要忘記:

db.commit() 
+0

我得到TypeError:'int'object has no attribute'__ getitem __' – itailitai

+0

@itailitai您的表格是否超過這三列? –

+1

@ pp_的解決方案[適用於我](http://ideone.com/8WKwAr)。 –