1. 程式人生 > >mysql資料匯入mongodb中

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!