我正在编写一个代理爬虫,它将数据存储在sqlite数据库中,我更喜欢通过语句保存一个复杂的对象,例如 然后我在这里cur.execute("insert into test(p) values (?)", (p,))
找到一个有用的官方文档官方文档
中的示例效果很好。
但是有一个问题来找我。
我将官方代码更改为:
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]
真的很奇怪。我想不通