如何通过Python将精确数据从MSSQL导入MongoDB

2024-05-03 07:45:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我想通过Python将数据从MicrosoftSQLServerManagementStudio(MSSQL)导入MongoDB(Robo3T)。“AvgWAC”列中的数据包含浮点数和“NULL”。如何解决如果数据是浮点数,它将在MongoDB中准确输出数字,但如果数据为“NULL”,它将在MongoDB中输出“None”

下面是我尝试过的python脚本,但它会抛出错误(不是NoneType)

def LastGenerationId(conn):
  GenerationId = 0
  cursor = conn.cursor()  
  cursor.execute("SELECT ISNULL(MAX(GenerationId),0) AS GenerationId FROM [XXX] ")  
  row = cursor.fetchone() 
  while row:
    GenerationId = row[0]
    row = cursor.fetchone()
  return GenerationId


def currencyCode(conn):
  cursor1 = conn.cursor()
  sql= ("SELECT DISTINCT [CurrencyCode] AS Currency FROM [xxx] WHERE [GenerationId]=%d ORDER BY [CurrencyCode] ")
  cursor1.execute(sql, GenerationId)
  row = cursor1.fetchone()
  curr = []
  while row:
    curr.append(row[0])
    row = cursor1.fetchone()
  return curr


GenerationId=int(LastGenerationId(conn))
currencies=currencyCode(conn)

for currency in currencies: 
  bals = []
  document = {"ProcessDt" :  datetime.datetime.utcnow(), "GenerationId": GenerationId ,"CurrencyCode":currency,"AverageWAC":[] }
  cursor2 = conn.cursor()
  cursor2.execute("SELECT [Name], [AvgWAC], [TransactionDate] FROM [xxx] where [CurrencyCode]='{}'and [GenerationId]='{}' ORDER BY TransactionDate" .format(currency, GenerationId) )
  row = cursor2.fetchone()
  while row:
        if (row[1])== "NULL":      
          baldict={"Name":str(row[0]),"AvgWAC":str(row[1]),"TransactionDate":str(row[2])}
          bals.append(baldict)
          row = cursor2.fetchone()
          document["AverageWAC"]=bals
        if (row[1])!="NULL":
          baldict={"Name":str(row[0]),"AvgWAC":float(row[1]),"TransactionDate":str(row[2])}
          bals.append(baldict)
          row = cursor2.fetchone()
          document["AverageWAC"]=bals


  x=col.insert_one(document)
conn.close()

Tags: 数据conndocumentnullcursorrowstrfetchone