整数字段不适用

2024-09-30 19:22:28 发布

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

我正在使用Python将Excel导入postgreSQL。下面是我遇到问题的领域。实际销售价格曾经是一个整数数据类型的值,但现在这个列包含了一个N/a值,这会破坏我的Python脚本。有什么我可以添加到这个脚本中,告诉它在不将数据类型更改为varchar的情况下引入N/A。在

import psycopg2
import xlrd
book = xlrd.open_workbook("T:\DataDump\8888.xlsx")
sheet = book.sheet_by_name("ProjectConsolidated")
database = psycopg2.connect (database = "***", user="****")
cursor = database.cursor()
delete = """drop table if exists "Python".ProjectConsolidated"""
print (delete)
mydata = cursor.execute(delete)

cursor.execute('''CREATE TABLE "Python".ProjectConsolidated
   (DCAD_Prop_ID VARCHAR(25),
   Actual_Close_Date date,
   Actual_Sales_Price integer,
   );''')
print "Table created successfully"

query = """INSERT INTO "Python".ProjectConsolidated (DCAD_Prop_ID,
   Actual_Close_Date,  Actual_Sales_Price) 
VALUES (%s, %s, %s)"""
for r in range(1, sheet.nrows):
DCAD_Prop_ID = sheet.cell(r,0).value
Actual_Close_Date = None if not sheet.cell(r,1).value else xlrd.xldate.xldate_as_datetime(sheet.cell(r,1).value,book.datemode)
Actual_Sales_Price = None if not sheet.cell(r,2).value else sheet.cell(r,2).value
values = (DCAD_Prop_ID,
   Actual_Close_Date,  Actual_Sales_Price)
cursor.execute(query, values)
cursor.close()
database.commit()
database.close()
print ""
print "All Done! Bye, for now."
print ""
columns = str(sheet.ncols)
rows = str(sheet.nrows)
print "I just imported Excel into postgreSQL" 

Tags: idclosedatevaluecellpricecursordatabase
1条回答
网友
1楼 · 发布于 2024-09-30 19:22:28
Actual_Sales_Price = None if not sheet.cell(r,61).value else sheet.cell(r,61).value

try:
    float(Actual_Sales_Price)
except (ValueError, TypeError):
    Actual_Sales_Price = None

如果python无法将实际销售价格转换为浮动(可能是因为它不是数字),我们将ASP更改为Null。在

您的DB驱动程序应该知道如何将pythonnone转换为Postgres。在

你是否真的希望实际销售价格在你的数据库是空的,这取决于你,虽然从提供的有限信息听起来是错误的。在

相关问题 更多 >