我寫這在SQLite數據庫中存儲數據的代理爬行,我更喜歡通過語句來保存複雜的物體,像cur.execute("insert into test(p) values (?)", (p,))
後來我找到一個有用的正式文件here
官方文檔中的例子效果很好。
但是有一個問題來找我。
我的官方代碼更改爲:
sqlite3.InterfaceError:錯誤綁定參數0 - 可能是不支持的類型
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]
這實在是odd.I無法弄清楚它
你錯過了在'__repr__'格式的元組括號。 – msw
@msw'__repr__'僅用於輸出 – Mithril