我正在编写一个代理爬虫,它将数据存储在sqlite数据库中,我更喜欢用cur.execute("insert into test(p) values (?)", (p,))
之类的语句保存一个复杂的对象。
然后我找到了一份有用的官方文件here
官方文件中的例子非常有效
但是我遇到了一个问题
我将官方代码更改为:
import sqlite3
import time
class 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 adapter
sqlite3.register_adapter(Proxy, adapt_proxy)
# Register the converter
sqlite3.register_converter("proxy", convert_proxy)
p = Proxy('231', '123', '2424','444','555',1,int(time.time()))
#########################
# 1) Using declared types
con = 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 names
con = 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()
发生错误:
Traceback (most recent call last):
File "C:\Users\kss\Desktop\py\ts1.py", line 52, in <module>
cur.execute("insert into test(p) values (?)", (p,))
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.
[Finished in 0.1s with exit code 1]
真的很奇怪。我想不出来了
答案 0 :(得分:1)
将您的代理声明更改为:
class Proxy(object):
# all the stuff before
问题是你的班级不是“新风格”班级;继承自object
使其成为一个。
注意documentation的说法:
要适应的类型/类必须是新式类,i。即它必须有 对象作为其基础之一。