当其中一个元素是Python字典时,在MySQL表中插入一行
我在将元素插入MySQL数据库时遇到问题 以下是我的代码:当其中一个元素是Python字典时,在MySQL表中插入一行,python,mysql,database,dictionary,insert,Python,Mysql,Database,Dictionary,Insert,我在将元素插入MySQL数据库时遇到问题 以下是我的代码: #!/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'
#!/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()
我的数据库是使用以下内容创建的:
CREATE TABLE MyTable(
'my_id' INT(10) unsigned NOT NULL,
'my_text' TEXT
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
正如您从python脚本中看到的,我列表中的一个元素是字典,它似乎停止了对MySQL数据库的插入,但由于我在最近几天才开始使用MySQL,我可能错了
如果我在myData
中创建myu text
一个简单的文本短语,如以下内容,一切正常,插入数据库表也正常:
myData = [ { u'my_text' : u'something simple', u'my_id' : u'1' } ]
我希望能够使用以下功能:
myData = [ { u'my_text' : {u'id': u'1', u'description' : u'described' }, u'my_id' : u'1' } ]
我做错了什么?你至少有两个选择
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)
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)
id
进行选择,因此数据更丰富
但是,如果您不需要将id与描述分开,那么第二种方法就可以工作,而无需更改表架构。您至少有两种选择
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)
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)
id
进行选择,因此数据更丰富
但是,如果不需要将id与描述分开,则第二种方法可以工作,而无需更改表架构。您只能在DB文本字段中插入文本。你希望那本字典看起来像什么,用字符串表示?你必须先把它转换成那样,然后再插入。我希望它能自动把字典转换成字符串。我该怎么做?您只能在DB文本字段中插入文本。你希望那本字典看起来像什么,用字符串表示?你必须先把它转换成那样,然后再插入。我希望它能自动把字典转换成字符串。我该怎么做呢?