我正在尝试将值插入到创建的表中 但是当我这样做时,它给我一个错误,说明未定义的变量 但我已在主函数中声明了它,并且值已分配给那些变量
这是我的代码。 #!的/ usr / bin中/ python3
import requests
import sqlite3
def get_info(url):
response = requests.get(url)
page = response.json()
name = page['name']
category = page['category']
link = page['link']
location = page['location']['city']
likes = page['likes']
checkins = page['checkins']
return name,category,link,location,likes,checkins
def main():
link = 'https://graph.facebook.com/Indiatoday'
p_name,p_cat,p_link,p_loc,p_likes,p_check = get_info(link)
print ('the page details are '+p_name,p_cat,p_link,p_loc,p_likes,p_check)
db = sqlite3.connect('page.db')
db.execute('''CREATE TABLE IF NOT EXISTS page_info (
id INTEGER PRIMARY KEY,
name TEXT,
category TEXT,
link TEXT,
location TEXT,
likes INTEGER,
checking INTEGER)''')
print ('table created successfully')
db.execute('''INSERT INTO page_info (name, category, link, location, likes,Checking) VALUES(?,?,?,?,?,?)''',(p_name,p_cat,p_link,p_loc,p_likes,p_check))
db.commit()
if __name__ == "__main__": main()
收到错误消息“NameError:name'p_name'未定义” 如果有人能让我知道我在这里做错了会很有帮助。我知道它是一个简单的变量定义,但我找不到它
答案 0 :(得分:0)
该行
db.execute('''INSERT INTO page_info (name, category, link, location, likes,Checking) VALUES(?,?,?,?,?,?)''',(p_name,p_cat,p_link,p_loc,p_likes,p_check))
在声明任何变量之前执行(因为它没有缩进,因此不属于main()
)。我认为你需要缩进整个块:
def main():
link = 'https://graph.facebook.com/Indiatoday'
p_name,p_cat,p_link,p_loc,p_likes,p_check = get_info(link)
print ('the page details are '+p_name,p_cat,p_link,p_loc,p_likes,p_check)
db = sqlite3.connect('page.db')
db.execute('''CREATE TABLE IF NOT EXISTS page_info (
id INTEGER PRIMARY KEY,
name TEXT,
category TEXT,
link TEXT,
location TEXT,
likes INTEGER,
checking INTEGER)''')
print ('table created successfully')
db.execute('''INSERT INTO page_info (name, category, link, location, likes,Checking) VALUES(?,?,?,?,?,?)''',(p_name,p_cat,p_link,p_loc,p_likes,p_check))
db.commit()