从两个列表创建一个sql表

时间:2014-05-09 12:12:17

标签: python sql list

我试图创建一个sql表: 我想给每个电影标题和评级一个id,并创建一个包含3个字段的表格 ¨

我的代码所以票价是:

import re
import sqlite3
#conn = sqlite3.connect('imdb.db')
#c = conn.cursor()

#c.execute('''CREATE TABLE imdb
         (mov_id, Title, Rating)''')

x = open("ratings.list.txt","r")
movread = x.readlines()
x.close()



#s = raw_input('Search: ').lower()
for ns in movread:


    if 'the lord of the' in ns.lower():
        d = re.split('\s+',ns,4)
        Title = d[4]
        Rating= d[3]

        list = [Title,Rating]
        print list
        # Insert a row of data
#c.execute("INSERT INTO imdb VALUES %r;" %(tuple(Rating)))")
#       conn.commit()

我的列表如下所示:

               Movie Title                                 Rating

['The Lord of the Rings: The Return of the King (2003)\n', '8.9']
['The Lord of the Rings: The Fellowship of the Ring (2001)\n', '8.8']
['The Lord of the Rings: The Two Towers (2002)\n', '8.7']

如何将其转换为SQL数据库?

2 个答案:

答案 0 :(得分:1)

如果您不想手动插入电影ID,请使用以下命令更改创建imdb表定义:

c.execute('''CREATE TABLE imdb (mov_id ROWID, Title, Rating)''')

允许您省略在插入中指定mov_id。

然后,只需使用

添加记录即可
c.execute('INSERT INTO imdb (Title, Rating) values ("%s","%s")'%(list[0],list[1]))

而不是# Insert a row of data行。

顺便说一句:如果你不需要,我会亲自对你的标题上的rstrip()删除换行符:

Title = d[4].rstrip()

答案 1 :(得分:0)

更新

import re
import sqlite3
conn = sqlite3.connect('imdb.db')
c = conn.cursor()

c.execute('''CREATE TABLE imdb (mov_id ROWID, Title, Rating)''')

x = open("ratings.list.txt","r")
movread = x.readlines()
x.close()



#s = raw_input('Search: ').lower()
for ns in movread:


    if 'the lord of the' in ns.lower():
        d = re.split('\s+',ns,4)
        Title = d[4].rstrip()
        Rating= d[3]

        list = [Title,Rating]

    # Insert a row of data
        c.execute('INSERT INTO imdb (Title, Rating) values ("%s","%s")'%(list[0],list[1]))
        conn.commit()
        for row in c.execute('SELECT * FROM imdb ORDER BY Title'):
            print row

输出:

    OperationalError                          Traceback (most recent call last)
 <ipython-input-598-0de924f55a23> in <module>()
     24 
     25         # Insert a row of data
---> 26         c.execute('INSERT INTO imdb (Title, Rating) values ("%s","%s")'%     (list[0],list[1]))
     27         conn.commit()
     28         for row in c.execute('SELECT * FROM imdb ORDER BY Title'):

 OperationalError: near "5": syntax error

(None, u'The Lord of the Rings: The Return of the King (2003)', u'8.9')
(None, u'The Lord of the Rings: The Fellowship of the Ring (2001)', u'8.8')
(None, u'The Lord of the Rings: The Return of the King (2003)', u'8.9')
(None, u'The Lord of the Rings: The Fellowship of the Ring (2001)', u'8.8')
(None, u'The Lord of the Rings: The Return of the King (2003)', u'8.9')
(None, u'The Lord of the Rings: The Two Towers (2002)', u'8.7')