簡體   English   中英

當其中一個元素是Python字典時,在MySQL表中插入一行

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

我在將元素插入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');
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創建my_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' } ]

我究竟做錯了什么?

您至少有兩個選擇。

  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) 
  2. 或更改傳遞給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) 

更改表架構的優勢在於,您現在可以基於id選擇,因此數據更加豐富。

但是,如果您不需要將ID與描述分開,則第二種方法將起作用,而無需更改表架構。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM