PythonSQLite3:强制将参数绑定为字符串?

2024-03-28 13:12:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python并没有实际的经验,但我想用它将CSV数据表转换成sqlite3db,认为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绑定成字符串?在


Tags: csv字符串textexecute参数fooas数字
1条回答
网友
1楼 · 发布于 2024-03-28 13:12:41

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,即使要插入整数数据,它仍将转换为文本并存储为文本。在

相关问题 更多 >