将Python字典/列表插入到SQL数据库中最有效的方法是什么? [英] What is the most effective way of Inserting Python dictionaries / lists into SQL database?

查看:2753
本文介绍了将Python字典/列表插入到SQL数据库中最有效的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



JSON示例:

 display_location:{
city:Bratislava,
state_name :斯洛伐克,
country_iso3166:SK,
纬度:48.20000076,
longitude:17.20000076,
}

然后,手动编写SQL插入是非常低效的:



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

(嗯,这五个值可以,但是想象中有五百个)



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

 为key,value在list.iteritems()中:
value_type = type value)
如果value_type为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)

之后插入看起来更简单:

  INSERT INTO conditions_bratislava(%s)VALUES%r%(keys_to_sql,tuple(vars_to_sql))

可以有数千个值,您仍然可以使用此一个insert语句。



请注意,解码Unicode字符串,所以你不会在每个值之前都有u字母。



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

解决方案

如果你的数据是这样的结构,一个文档导向的数据库(Mongo / Couch等)



你可以得到这样的东西...我想使用 repr 有点太聪明了...

  insert_sql ='INSERT INTO conditions_bratislava(%s)values (%s)'
cols =','.join(somedict)
vals =','.join('?'* len(somedict))#或者需要qparam
to_execute = insert_sql%(cols,vals)
some_cursor.execute(to_execute,somedict.values())

在旁注:

  value_type = type(value)
如果value_type为unicode:

应写为:

  if isinstance(value,unicode):


Imagine you have a key-value Python dictionary (or list) with larger amounts of items. Let’s say you’re reading a bigger JSON file and you’d like to store it’s contents into MySQL table with keys as names of columns and values as values itself.

JSON Example:

"display_location": {
    "city":"Bratislava",
    "state_name":"Slovakia",
    "country_iso3166":"SK",
    "latitude":"48.20000076",
    "longitude":"17.20000076",
}

Then it is quite inefficient to write SQL insert like this manually:

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

(Well, it's ok with five values, but imagine there are for example five hundreds of them.)

Is there any Python class / method for effective and short-stringed SQL insert? I wrote this piece of code:

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)

After that the insert looks much more simple:

INSERT INTO conditions_bratislava(%s) VALUES %r" % (keys_to_sql,  tuple(vars_to_sql),)

There can be thousands of values and you will still be fine with this one insert statement.

Note that condition which will decode Unicode strings, so you won’t have "u" letters before the each value.

So, is there any more effective and prepared class or method how to insert many values in the same simple approach with short INSERT string?

解决方案

If your data is structured like that, it would lend itself more towards a document orientated database (Mongo/Couch etc...)

You can get away with something like this... I think using repr is being a little too clever...

insert_sql = 'INSERT INTO conditions_bratislava(%s) values(%s)'
cols = ', '.join(somedict)
vals = ', '.join('?' * len(somedict)) # or whatever qparam is required
to_execute = insert_sql % (cols, vals)
some_cursor.execute(to_execute, somedict.values())

On a side note:

value_type = type(value)
if value_type is unicode:

Should be written as:

if isinstance(value, unicode):

这篇关于将Python字典/列表插入到SQL数据库中最有效的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆