sqlite3 adaptors mystery
Mel
mwilson at the-wire.com
Sun Mar 2 07:25:18 EST 2008
Matej Cepl wrote:
> Thanks for your help, but plain-text strings is not what
> I wanted. The boolean variables was what I was after. See this
> modified version of the script:
>
> #!/usr/bin/python
> import sqlite3
> def adapt_boolean(bol):
> if bol:
> return "True"
> else:
> return "False"
>
> def convert_boolean(bolStr):
> if str(bolStr) == "True":
> return bool(True)
> elif str(bolStr) == "False":
> return bool(False)
> else:
> raise ValueError, "Unknown value of bool attribute
> '%s'" % bolStr
>
> sqlite3.register_adapter(bool,adapt_boolean)
> sqlite3.register_converter("boolean",convert_boolean)
>
> db = sqlite3.connect(":memory:")
> cur=db.cursor()
> cur.execute("create table test(p boolean)")
> p=False
> cur.execute("insert into test(p) values (?)", (p,))
> p=True
> cur.execute("insert into test(p) values (?)", (p,))
> cur.execute("select p from test")
> for (field,) in cur.fetchall():
> print field,type(field)
>
> The output here is:
>
> [matej at viklef dumpBugzilla]$ python testAdaptors.py False <type
> 'unicode'>
> True <type 'unicode'>
> [matej at viklef dumpBugzilla]$
>
> I thought that converter is there for just exactly this -- that
> I would get back bool values not strings.
>
> Sorry for not being clear in the first run.
Sorry about the misunderstanding. It seems you want
db = sqlite3.connect("test.db", detect_types=sqlite3.PARSE_DECLTYPES)
After this, the print shows
False <type 'bool'>
True <type 'bool'>
Mel.
More information about the Python-list
mailing list