Как преобразовать тип Python 'None' в тип 'NULL' - PullRequest
0 голосов
/ 05 июня 2018

Как преобразовать тип Python 'None' в тип 'NULL'?Я запрашиваю Vertica DB, используя модуль python-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()

1 Ответ

0 голосов
/ 06 июня 2018

Если проблема заключается в том, что вы хотите использовать NULL в качестве токена, просто добавьте замену, как у вас, для 0.0.

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

Затем измените свою копию для размещения.

null as 'NULL'
...