相关疑难解决方法(0)

为什么在Python中不推荐使用MutableString?

为什么在Python 2.6中不推荐使用MutableString类;
为什么它在Python 3中删除了?

python string mutable deprecated python-3.x

19
推荐指数
2
解决办法
5566
查看次数

将Python词典/列表插入SQL数据库的最有效方法是什么?

想象一下,你有一个包含大量项目的键值Python字典(或列表).假设您正在阅读更大的JSON文件,并且您希望将其内容存储到MySQL表中,其中键作为列的名称,值作为值本身.

JSON示例:

"display_location": {
    "city":"Bratislava",
    "state_name":"Slovakia",
    "country_iso3166":"SK",
    "latitude":"48.20000076",
    "longitude":"17.20000076",
}
Run Code Online (Sandbox Code Playgroud)

那么手动编写这样的SQL插入是非常低效的:

INSERT INTO TABLE (city, state_name, country_iso3166, latitude, longitude) VALUES('%s','%s','%s','%s','%s')
% (Bratislava, Slovakia, SK, 48.20000076, 17.20000076);
Run Code Online (Sandbox Code Playgroud)

(嗯,五个值都可以,但想象一下有五百个值.)

是否有任何用于有效和短弦SQL插入的Python类/方法?我写了这段代码:

for key,value in list.iteritems():
  value_type = type(value)
    if value_type is unicode:
      vars_to_sql.append(value.encode('ascii', 'ignore'))
      keys_to_sql.append(key.encode('ascii', 'ignore'))
    else:
      vars_to_sql.append(value)
      keys_to_sql.append(key)

keys_to_sql = ', '.join(keys_to_sql)
Run Code Online (Sandbox Code Playgroud)

之后插入看起来更简单:

INSERT INTO conditions_bratislava(%s) VALUES %r" % (keys_to_sql,  tuple(vars_to_sql),)
Run Code Online (Sandbox Code Playgroud)

可以有数千个值,你可以使用这一个insert语句.

请注意将解码Unicode字符串的条件,因此在每个值之前不会有"u"字母.

那么,是否有更有效和准备的类或方法如何使用短INSERT字符串在同一简单方法中插入许多值?

python sql json dictionary insert

10
推荐指数
1
解决办法
3581
查看次数

标签 统计

python ×2

deprecated ×1

dictionary ×1

insert ×1

json ×1

mutable ×1

python-3.x ×1

sql ×1

string ×1