【问题标题】:Insert unicode value into sqlite from python code从python代码将unicode值插入sqlite
【发布时间】:2014-07-30 15:41:55
【问题描述】:

我有以下查询用于将值插入到 sqlite3 db 中,这是用 python 代码制作的;

insert into 'SplCharTest' ('Id','name','address','telefon') values (1.0, u'cust01', u'addr01  strasse 48908', 2131234213.0)

当我尝试执行此查询时出现以下错误;

sqlite3CursorObj.execute(dataInsertQueryForSheet)
sqlite3.OperationalError: near "'cust01'": syntax error

我注意到 'cust01' 前面的 u (unicode) 是问题所在。谁能告诉我如何将 unicode 值插入 sqlite db。无法简单使用“str”,因为我使用 openpyxl 包从 excel 文件中获取 unicode 值,并且可能存在特殊字符。

下面是我的python代码

dataInsertQueryForSheet = "insert into '"+tableNameForSheet+"' ("+columnNamesCSV+") values (%s)" % unicode(rowDataList)[1:(rowDataStrLen-1)]
sqlite3CursorObj.execute(dataInsertQueryForSheet)

这里变量tableNameForSheet 包含表名,columnNamesCSV 包含CSV 格式的所有列名,rowDataList 包含要作为数组列表插入的所有值。

任何帮助将不胜感激。提前致谢。

【问题讨论】:

  • 您可能不想在电话号码中使用浮点数,尤其是因为sqlite will give at least 16 digits in an integer]。更好的是,使用文本类型,因为电话号码没有任何数字(除了它们是数字字符串)。
  • @msw - 感谢您的推荐。

标签: python sqlite unicode


【解决方案1】:

SQLite 总是使用 Unicode。

在避免格式化问题或 SQL 注入攻击的同时使用字符串的最简单方法是使用参数:

sql = "insert into "+tableNameForSheet+" ("+columnNamesCSV+") values (?,?,?,?)"
parameters = [1, u'cust01', u'addr01  strasse 48908', "2131234213"]
cursor.execute(sql, parameters)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-24
    相关资源
    最近更新 更多