【问题标题】:SQLite: Can not insert data into tableSQLite:无法将数据插入表中
【发布时间】:2022-01-05 10:13:14
【问题描述】:

我想将此字典“all_movies”插入到表“movie_table”中。

使用 asyncio 对数据进行网络抓取,然后将其收集到 original_movies 中。

"CREATE TABLE IF NOT EXISTS movie_table 
(actor_rank INTEGER, movie_name TEXT, year TEXT, genre TEXT, rating TEXT);"

我尝试了多种方法,但出现以下错误:

1.错误:

sqlite3.ProgrammingError: Incorrect number of bindings supplied. 
The current statement uses 5, and there are 65 supplied.

使用此查询(original_movie 已更改)

insertQuery = '''INSERT INTO 
movie_table (actor_rank, movie_name, year, genre, rating) VALUES (:actor_rank, :movie_name, :year, :genre, :rating)'''
            
cursor.executemany(insertQuery, original_movie)
connection.commit()

2。错误:

sqlite3.ProgrammingError: Incorrect number of bindings supplied. 
The current statement uses 5, and there are 1 supplied.

使用此查询(original_movie 已更改)

insertQuery = '''INSERT INTO 
movie_table (actor_rank, movie_name, year, genre, rating) VALUES (:actor_rank, :movie_name, :year, :genre, :rating)'''
            
cursor.executemany(insertQuery, [original_movie])
connection.commit()

3.错误:

sqlite3.ProgrammingError: Incorrect number of bindings supplied. 
The current statement uses 5, and there are 65 supplied.

使用此查询(VALUES 已更改,并且 original_movies 现在是包含元组的列表)

insertQuery = '''INSERT INTO 
movie_table (actor_rank, movie_name, year, genre, rating) VALUES (?, ?, ?, ?, ?)'''
            
cursor.executemany(insertQuery, original_movie)
connection.commit()

【问题讨论】:

    标签: python database sqlite


    【解决方案1】:

    据我了解, original_movie 是一个字典列表。所以你可以做这样的事情

    for movie in original_movie:
        insertQuery = '''INSERT INTO movie_table (actor_rank, movie_name, year, genre, rating) VALUES (:actor_rank, :movie_name, :year, :genre, :rating)'''
                
        cursor.execute(insertQuery, (**movie,))
        connection.commit()
    

    或者你可以重写 get_actors_movies func 来使用 executemany 方法

    def get_actors_movies():
    for ... in ...:
          movie_data = [ index,
                         movie.find('a', href=True).text.strip(),
                         movie.find('span').text.strip(),
                         movie_soup.find('span', class_=re.compile('ipc-chip__text')).text,
                         'TO-DO'
                  ]
          all_movies.append(movie_data)
    return all_movies
    
    ...
    
    insertQuery = '''INSERT INTO movie_table (actor_rank, movie_name, year, genre, rating) VALUES (?, ?, ?, ?, ?)'''
            
    cursor.executemany(insertQuery, original_movie)
    connection.commit()
    

    【讨论】:

    • 我收到cursor.execute(insertQuery, (**movie,)) 的语法错误。使用第二种解决方案,我收到错误 sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 5, and there are 65 supplied.
    猜你喜欢
    • 2011-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-18
    相关资源
    最近更新 更多