简体   繁体   English

当其中一个元素是Python字典时,在MySQL表中插入一行

[英]Insert a row into a MySQL table when one of the elements is a Python dictionary

I am having trouble inserting an element into a MySQL database. 我在将元素插入MySQL数据库时遇到麻烦。

Here is the code I have: 这是我的代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-

myData = [ { u'my_text' : {u'id': u'1', u'description' : u'described' }, u'my_id' : u'1' } ]

import MySQLdb as mdb
con = None
con = mdb.connect('localhost', 'abc', 'def', 'ghi');
cur = con.cursor()
con.set_character_set('utf8')
cur.execute('SET NAMES utf8;')
cur.execute('SET CHARACTER SET utf8;')
cur.execute('SET character_set_connection=utf8;')

sql = "INSERT IGNORE INTO MyTable ( 'my_id', 'my_text' ) VALUES ( %(my_id)s, %(my_text)s );"
cur.executemany(sql, myData)
con.commit()

if con: con.close()

My database is created with this: 我的数据库就是这样创建的:

CREATE TABLE MyTable(
    'my_id' INT(10) unsigned NOT NULL,
    'my_text' TEXT
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

As you can see from the python script one element of my list is a dictionary and it seems to be this that is stopping the insertion into the MySQL database but as I have only started using MySQL in the last few days I may be wrong. 正如您从python脚本中看到的那样,列表中的一个元素是字典,这似乎阻止了插入MySQL数据库,但是由于最近几天我才开始使用MySQL,所以我可能是错的。

If I make my_text within myData a simple text phrase such as the following everything works fine and the insertion into the database table works fine: 如果我在myData创建my_text一个简单的文本短语,例如以下内容,则一切正常,并且插入数据库表中的情况也很好:

myData = [ { u'my_text' : u'something simple', u'my_id' : u'1' } ]

I want to be able to use this: 我希望能够使用此:

myData = [ { u'my_text' : {u'id': u'1', u'description' : u'described' }, u'my_id' : u'1' } ]

What am I doing wrong? 我究竟做错了什么?

You have at least two choices. 您至少有两个选择。

  1. Change your table schema: 更改表架构:

     CREATE TABLE MyTable( 'my_id' INT(10) unsigned NOT NULL, 'id' INT(10), 'description' TEXT ) ENGINE=MyISAM DEFAULT CHARSET=utf8 sql = "INSERT IGNORE INTO MyTable ( 'my_id', 'id', 'description' ) VALUES ( %s, %s, %s )" myArg = [(dct['my_id'], dct['my_text']['id'], dct['my_text']['description']) for dct in myData] cur.executemany(sql, myArg) 
  2. or change the arg passed to cur.executemany : 或更改传递给cur.executemany的arg:

     myData = [ { u'my_text' : {u'id': u'1', u'description' : u'described' }, u'my_id' : u'1' } ] myArg = [ {'my_txt' : str(dct['my_text']), 'my_id' : dct['my_id']} for dct in myData ] cur.executemany(sql, myArg) 

The advantage of changing the table schema is that you can now select based on id , so the data is richer. 更改表架构的优势在于,您现在可以基于id选择,因此数据更加丰富。

But if you have no need to separate the id from the description, then the second way will work without having to change the table schema. 但是,如果您不需要将ID与描述分开,则第二种方法将起作用,而无需更改表架构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM