使用python将字典列表插入到SQL表中

时间:2015-11-10 17:41:27

标签: python sql python-3.x

我正在使用python和sql数据库进行第一步,但仍不确定要使用哪个包以及如何使用。我有一个大约300k字典的列表,每个字典大约有20个键。这些dicts应插入SQL表中。

在我看来,dict方法列表的优点是,我明确地命名了我想要输入特定值的列。 (可能是,这不是一个好方法)

让我提出一个更具体的例子来捕捉我的问题的基本要素。 该表由三列组成:ID(整数),Price(十进制),Type(字符串)。 Type支持空值。

我的dict的键具有相同的名称,而dicts的列表可能如下所示:

lst = [{'ID':1, 'Price': '9.95', 'Type': None}, 
       {'ID':2, 'Price': '7.95', 'Type': 'Sports'}, 
       {'ID':3, 'Price': '4.95', 'Type': 'Tools'}, ...]

所以出现的问题如下:

  1. 使用dicts的方法是正确的吗? (请注意,我有20列)
  2. 如果是/否:如何有效地执行此类查询?
  3. 是否有必要将价格转换为十进制和SQL语句之前,或者可以“即时”实现这一目标
  4. None值是自动转换为null,还是需要做额外的工作?

3 个答案:

答案 0 :(得分:3)

假设您使用的是Python Database API specification兼容的数据库驱动程序。

类型转换(问题3和4)应由开箱即用的数据库驱动程序处理。

至于2),有executemany()

cursor.executemany("""
    INSERT INTO 
        mytable
        (id, price, type)
    VALUES
        (%(id)s, %(price)s, %(type)s)
""", lst)

答案 1 :(得分:1)

mydb = MySQLdb.connect(host='',    # your host_name
                       user='',    # your username
                       passwd='',  # your password
                       db=''       # your database
                       )
cur= mydb.cursor()
insert_query = "INSERT INTO table_name(feild_1,feild2,feild3) VALUES ( %(id)s, %(price)s, %(type)s);"
cur.executemany(insert_query, lst)
mydb.commit

答案 2 :(得分:0)

回答您的问题:

  • 使用字典列表没问题
  • 下面是处理您的案例的完整应用程序
  • 不需要将价格转换为十进制,在这个例子中,我们在 MySQL 中声明价格为十进制,但在列表中,它被设置为字符串,也被设置为整数,但保存为十进制
  • None 值自动转换为 null
from tkinter import *
import mysql.connector as myConnector
from tkinter import messagebox
from mysql.connector import Error
def insert(table,lst):

    myList = listNestedDictForTblInsert(lst)
    print(myList)
    
    mySqlStr = f'INSERT INTO {table}(ID, Price, Type) VALUES(%s,%s,%s)' 
    val = myList
    print(mySqlStr)
    print(val)
    myDb = myConnector.connect(host='localhost',
                               database = "libraryDb2",
                               user='root',
                               password='dhso')
    try:
       myCursor = myDb.cursor()
       myCursor.executemany(mySqlStr, val)
       myDb.commit()
       messagebox.showinfo("show info", "Data is saved successfully")
    except Error as e:
       messagebox.showinfo("show info", "Data is not saved")

    myDb.close()
    myCursor.close()


def listNestedDictForTblInsert(data):
#Convert the list of dictionaries into list of tuples
   myList = []
   for i in range(len(data)):
      myList1 = []
      for value in (data[i].values()):
         myList1.append(value)
      myList1 = tuple(myList1)   
      myList.append(myList1)
   return myList
#Output myList:
#[('Ralph', 45), ('Betty', 50), ('Joey', 45), ('Heather', 25)]
           
root = Tk()

lst = [{'ID':1, 'price': 9.95, 'type': None}, 
       {'ID':2, 'Price': '7', 'type': 'Sports'}, 
       {'ID':3, 'Price': 4, 'Type': 'Tools'}]
table = 'test1'
root.title("Testing Part")
btn = Button(root, text = "Insert Dictionary in MYSQL Table", width = 30, command = lambda : insert(table, lst))
btn.pack()
root.mainloop

Application window

mysql table test1 Stored data in table

相关问题