Python:“NoneType”对象在非空查询结果上不可订阅,怎么办?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (221)

我得到object is not subscriptable在非空查询结果上。当我输出c.fetchone()它会输出正确的结果,但是当我检查类型时,它会说<class 'NoneType'>

import sqlite3

conn = sqlite3.connect("scraping.db")
c = conn.cursor()

c.execute('CREATE TABLE IF NOT EXISTS Terminate (numar INT, arj INT )')
conn.commit()
c.execute('DELETE FROM Terminate')
conn.commit()
c.execute('INSERT OR IGNORE INTO Terminate ( numar, arj ) VALUES (1,0)')
conn.commit()
c.execute("SELECT * FROM Terminate") # ORDER BY numar DESC LIMIT 1")
print(c.fetchone(), type(c.fetchone()))

ins = c.fetchone()[0]
提问于
用户回答回答于

发生这种情况是因为你已经在输出中获取了两个值。你要重新执行、选择或删除输出:

import sqlite3

conn = sqlite3.connect("scraping.db")
c = conn.cursor()

c.execute('CREATE TABLE IF NOT EXISTS Terminate (numar INT, arj INT )')
conn.commit()
c.execute('DELETE FROM Terminate')
conn.commit()
c.execute('INSERT OR IGNORE INTO Terminate ( numar, arj ) VALUES (1,0)')
conn.commit()
c.execute("SELECT * FROM Terminate") # ORDER BY numar DESC LIMIT 1")


ins = c.fetchone()[0]
print ins, type(ins)

输出似乎没问题

1 <type 'int'>

扫码关注云+社区

领取腾讯云代金券