我正在编写一个将爬虫存储在sqlite数据库中的数据的代理爬网程序,并且我更喜欢通过像cur.execute("insert into test(p) values (?)", (p,))这样的语句保存一个复杂的对象, 然后在这里找到有用的官方文档。官方文档中的示例非常有效。但是我有一个问题。我将官方代码更改为:import sqlite3import timeclass Proxy: def __init__(self,ip,port,speed,area,level,active,last_check_time): self.ip = ip self.port = port self.speed = speed self.area = area self.level = level self.active = active self.last_check_time = last_check_time def __repr__(self): return '%s;%s;%s;%s;%s;%d;%d' % (self.ip,self.port,self.speed,self.area,self.level,self.active,self.last_check_time)def adapt_proxy(proxy): return '%s;%s;%s;%s;%s;%d;%d' % (proxy.ip,proxy.port,proxy.speed,proxy.area,proxy.level,proxy.active,proxy.last_check_time)def convert_proxy(s): ip,port,speed,area,level,active,last_check_time = map(str, s.split(";")) return Proxy(ip,port,speed,area,level,int(active),int(last_check_time))# Register the adaptersqlite3.register_adapter(Proxy, adapt_proxy)# Register the convertersqlite3.register_converter("proxy", convert_proxy)p = Proxy('231', '123', '2424','444','555',1,int(time.time()))########################## 1) Using declared typescon = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)cur = con.cursor()cur.execute("create table test(p proxy)")cur.execute("insert into test(p) values (?)", (p,))cur.execute("select p from test")print "with declared types:", cur.fetchone()[0]cur.close()con.close()######################## 1) Using column namescon = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES)cur = con.cursor()cur.execute("create table test(p)")cur.execute("insert into test(p) values (?)", (p,))cur.execute('select p as "p [proxy]" from test')print "with column names:", cur.fetchone()[0]cur.close()con.close()
1 回答
largeQ
TA贡献2039条经验 获得超7个赞
将您的代理声明更改为:
class Proxy(object):
# all the stuff before
问题在于您的课程不是“新样式”课程;继承object使之成为一体。
请注意文档中的内容:
要适应的类型/类必须是新式类,即它必须以object作为其基础之一。
添加回答
举报
0/150
提交
取消