Python和sqlite3:将矩阵插入表中

时间:2016-03-03 19:06:17

标签: python matrix sqlite sql-insert

我们说我有这个矩阵:

[[[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

1 个答案:

答案 0 :(得分: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()