如何将 Python 'None' 类型转换为 'NULL' 类型

How to convert Python 'None' type to 'NULL' type

如何将Python'None'类型转换为'NULL'类型?我正在使用 python-vertica 模块查询 Vertica 数据库,并将结果集写入 CSV 文件,其中 Python CSV 模块将 NULL 插入为 None。因此,当我将此 CSV 文件导入 Vetica 数据库时,我得到的空字符串为 ' ',其中我希望它为 NULL。我猜这里的问题是因为 Python None 类型。我该如何解决这个问题?

以下是将数据导出为 CSV 的代码:

def get_data(table, startDate, endDate, config):
  connFrom = vertica_connect_from(config)
  cursor = connFrom.cursor()

  if startDate == endDate:
      command = "select * from dev.{} where report_date='{}'".format(table,startDate)
  else:
      command = "select * from dev.{} where report_date between '{}' and '{}'".format(table, startDate, endDate)

  cursor.execute(command)
  rows = cursor.fetchall()

  with open(filePath, 'w') as csvfile:
      writer = csv.writer(csvfile, delimiter="|")
      for row in rows:
          for index, item in enumerate(row):
              if (item == 0.0):
                  row[index] = 0
          writer.writerow(row)
      logger.info('Data has been copied and written to CSV file at %s', filePath)

  connFrom.close()

这是我导入它的方式:

def load_data(table, config):
  connTo = vertica_connect_to(config)
  cur = connTo.cursor()

  importCommand = "copy qa.{} from stdin null as '' rejected data '{}' exceptions '{}'".format(table,rejectedLog, exceptionLog)
  with open(filePath, 'r') as fil:
      try:
          cur.copy(importCommand, fil)
      except Exception as e:
          logger.error('%s', e)
      logger.info('Data has been copied, check rejected/exception files at /tmp on the destination host for any errors')

  connTo.close()

如果这里的问题是您想使用 NULL 作为标记,只需添加一个替换项,就像您对 0.0.0 所做的那样。

if not item: 
    row[index] = 'NULL'

然后更改您的副本以适应。

null as 'NULL'