我正在编写一个将爬虫存储在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()
largeQ
相关分类