首页 > 解决方案 > 使用 python 创建 SQLite 数据库时出现意外错误

问题描述

import json
import urllib
import sqlite3

import temp


def loading():
    url = 'https://jobs.github.com/positions.json?page=1'  # URL for API 1-5json_obj = urllib.urlopen(url)
    response = urllib.urlopen(url)
    data = json.load(response)  # loads the url and set it into data variable

    for item in data[0].keys():
        print(item)
        return data  # Get the keys


# def loading():
# print " LOADING API(s)"
# urllib.urlopen('https://jobs.github.com/positions.json?page=1')
# temp = json.dumps(data[1])
# print (json.dumps(data[1]))
# print (" ")
def createDB(data):
    conn = sqlite3.connect('test.db')
    c = conn.cursor()
    # Create table
    c.execute('''CREATE TABLE example
        (description text, title text, url text, company_logo text, company text, id integer primary key, company_url text, how_to_apply text,
        location text, type text, created_at timestamp)''')
    temp_values = list(tuple())
    for item in temp:

        list_of_values = [v for k, v in item.items()]
        tuple_of_values = tuple(list_of_values)
        temp_values.append(tuple_of_values)
        c.executemany('INSERT INTO table_name VALUES (?,?,?,?,?,?,?,?,?,?,?)', temp_values)


def main():
    data = loading()
    createDB(data)


main()

我运行了它创建数据库的代码,但其中似乎没有任何内容,这也是我得到的错误文件

回溯(最后一次调用):文件“/Users/issac_rodriguez/PycharmProjects/N/Sprint2/database.py”,第 45 行,在 main() 文件“/Users/issac_rodriguez/PycharmProjects/N/Sprint2/database.py”中,第 42 行,在主 createDB(data) 文件“/Users/issac_rodriguez/PycharmProjects/N/Sprint2/database.py”中,第 32 行,在 createDB 中为 temp 中的项目:TypeError: 'module' object is not iterable

标签: pythonsqldatabaseapi

解决方案


看看你的createDB()函数的循环。您尝试遍历tempwhich 指的是您在上面导入的模块 temp。也许您打算遍历temp_values?您可能还需要将您的论点传递datatemp_values. 这是一个潜在的解决方案:

temp_values = list(tuple(data))
for item in temp_values:
...

希望这可以帮助!


推荐阅读