0

我正在编写一个代理爬虫,它将数据存储在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]

真的很奇怪。我想不通

4

1 回答 1

1

将您的代理声明更改为:

class Proxy(object):
    # all the stuff before

问题是您的课程不是“新式”课程;继承自object使它成为一个。

注意文档是如何说的:

要适应的类型/类必须是新式类,即它必须有对象作为其基础之一。

于 2013-06-24T04:30:58.533 回答