我实际上没有Python经验,但是想用它将CSV数据表转换为sqlite3 db,认为python会很完美。我遇到了一个问题:有一个我想绑定为字符串的参数,但是如果它“看起来”像一个数字,它将以int的形式存储到数据库中,删除前导零...我正在尝试处理电话号码这里...
c.execute( "CREATE TABLE foo (a text, b text)" )
...
strA = "069-888888" # bound as string
strB = "069777777" # bound as int, value in db is 697777777
c.execute( "INSERT INTO foo (a,b) values (?,?)", [strA, strB] )
有没有办法强制将strB绑定为字符串?
最佳答案
SQLite可以很好地处理这种情况:
>>> import sqlite3
>>> conn = sqlite3.connect('/tmp/test.db')
>>> cur = conn.cursor()
>>> cur.execute('CREATE TABLE foo (a text, b text)')
>>> strA = "069-888888"
>>> strB = "069777777"
>>> cur.execute('INSERT INTO foo (a,b) values (?,?)', (strA, strB))
>>> cur.execute('select * from foo;')
<sqlite3.Cursor object at 0x1101c39d0>
>>> cur.fetchall()
[(u'069-888888', u'069777777')]
换句话说:这里没有问题。
SQLite 3使用type affinity而不是固定类型进行操作,但是由于您将列声明为
TEXT
,即使您要插入整数数据,它也仍将转换为文本并以这种方式存储。关于python - Python sqlite3:强制将参数绑定(bind)为字符串?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18231657/