mysql数据导入mongodb中

# 把mysql数据库中的数据导入mongodb中
import pymysql
import pymongo

# 创建mysql的数据库连接
con = pymysql.connect(host='localhost', port=3306, user='root', password='123456', db='pp')
# 获取游标
cur = con.cursor(cursor=pymysql.cursors.DictCursor)
# 查询student表
try:
  cur.execute('select * from student')
  # 创建mongodb数据库连接
  client = pymongo.MongoClient(host='localhost', port=27017)
  # 获取数据库
  db = client['pp']#或者db=client.pp,相当于数据库中的use pp;
  for row in cur.fetchall():
    row['birthday'] = str(row['birthday']) #因为mongodb没有datetime类型,因此必须先转为字符串才能导入mongodb,否则可省略此步
    db.student.insert_one(row)
except Exception as e:
  print(e)
finally:
  con.close()
  client.close()
#The achievement is attributed to teacher Peng!

猜你喜欢

转载自www.cnblogs.com/zpdbkshangshanluoshuo/p/10065311.html