python - 将mysql记录/行放入字典中

时间:2015-09-01 15:23:20

标签: python mysql postgresql dictionary database-migration

我们的团队正在开发新版本的webapp。与旧版本的主要区别之一是使用的DBMS。支持的设计者决定跳过mysql到postgresql。除此之外,还更新了db结构/模式。

我开始处理python脚本,该脚本将负责迁移" old"的数据。客户。

(问)我的主要问题是我选择正确的方法来解决这个问题吗?

"大图"计划(不是我知道的那么大)如下:

  • 在客户服务器上安装python和依赖项。

  • 自旧webapp需要后,mysql将出现在服务器上

  • 安装postgresql并使用其空结构创建新数据库

  • 运行python脚本。

python脚本将处理以下操作:

  • 与两个DBMS打开连接
  • 从mysql中选择某种数据,并将每一行放入字典
  • 处理/操纵数据,以使其与新数据库兼容
  • 将固定数据插入postgresql数据库

(问)我的第二个问题是,python词典是一个合适的数据结构,可以做我想做的事情吗?

不幸的是,我已经停留在第二个/第三个要点("将每个mysql行放入字典并操纵数据")。我的脚本目前看起来如下(我知道我的python不是那么好)。

#!/usr/bin/python

# ------------------------------
# import of standard libraries |
# ------------------------------
#
import os
import sys
import mysql.connector
import psycopg2
from pprint import pprint
import MySQLdb

# ------------------------------
# import of internal snippets  |
# ------------------------------
#
from include.db_config import *
#from include.MySQLCursorDict import *

# ------------------------------
# Community Migration          |
# ------------------------------
#
cnx = mysql.connector.connect( host=host_mysql, user=user_mysql, passwd=pswd_mysql, db=dbna_mysql )
cur = cnx.cursor()
cur.execute("SELECT * from elements where type=1")

result = []
columns = tuple( [d[0].decode('utf8') for d in cur.description] )

for row in cur:
  result.append(dict(zip(columns, row)))

pprint(result)

cur.close()
cnx.close()

问题是我真的不确定我是否使用此代码获得了真正的字典,因为我没有成功操作数据(例如更改列名)PS:密钥dict是mysql记录中的列名,所有值都是字段。

(问)是否有人知道将mysql记录放入字典中的正确方法,以便能够轻松地#34;操纵它?

提前感谢您提供任何帮助

0 个答案:

没有答案