尝试语句错误

时间:2016-10-07 20:20:59

标签: python excel

我是Python新手,我正在将Excel数据导入postgreSQL。我的Excel中有空白空格用于Traffic和Week_Ending列。 Try语句似乎对Week_Ending运行良好,但对于Traffic它会抛出一个错误。我检查了Excel,由于其中一个单元格中有一个空白空格,错误显示出来。我认为它适用于两个列,但它不适用于流量。任何人都可以提供帮助。

import psycopg2
import xlrd
import datetime
book = xlrd.open_workbook("T:\DataDump\8888.xlsx")
sheet = book.sheet_by_name("Builder_Traffic")
database = psycopg2.connect (database = "***", user="*")

cursor = database.cursor()
delete = """Drop table if exists "Python".buildertraffic"""
print (delete)
mydata = cursor.execute(delete) 




cursor.execute('''CREATE TABLE "Python".buildertraffic
   (Builder_Name varchar(55),   
Traffic integer,
Week_Ending date,
Project_ID integer
   );''')

print "Table created successfully"

query = """INSERT INTO "Python".buildertraffic (Builder_Name, Traffic,  Week_Ending, Project_ID)
VALUES (%s, %s, %s, %s)"""

for r in range(1, sheet.nrows):
    Builder_Name = sheet.cell(r,0).value
    Traffic = None
    try:
        Traffic = (sheet.cell(r,1).value)
    except:
        pass
    Week_Ending = None
    try:
        Week_Ending = xlrd.xldate.xldate_as_datetime(sheet.cell(r,2).value,book.datemode)
    except:
        pass
    Project_ID = sheet.cell(r,3).value

values = (Builder_Name, Traffic, Week_Ending, Project_ID)
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" 

错误显示为:

Traceback (most recent call last):
File   "C:\Users\aqureshi\Desktop\Programming\PythonSQLNew\BuilderTraffic.py", line 47, in <module>
DataError: invalid input syntax for integer: " "
LINE 2: VALUES ('American Legend Homes', ' ', NULL, 2.0)
                                     ^

1 个答案:

答案 0 :(得分:0)

您应该检查该列中的空白或空字符串:

traffic = sheet.cell(r, 1).value

我在您的代码中没有看到您实际执行查询的方式,但是您应该在int中包含流量以解析字符串中的整数:How to convert strings into integers in Python?

try:
    traffic = int(sheet.cell(r, 1).value)
except:
    traffic = -1 # or 0? some value to indicate this has NO traffic.