将日期对象与字符串一起上载到SQL db时出错

时间:2014-06-04 12:58:17

标签: python sql

我有date object需要从CSV文件上传到数据库中。当我进行查询以将行上传到DB时。我收到这个错误:

Incorrect syntax near the keyword 'of'. (156) (SQLExecDirectW)")

上传数据的代码:

with open(UploadFile, "r") as uploadData:
    i = 0
    flag = 0
    formatter_string = "%d/%m/%y"
    for row in reader:
        if(flag == 0):
            flag = flag + 1
        else:
            datetime_object = datetime.strptime(row[0], formatter_string)
            row[0] = datetime_object.date()

        cursor.execute("insert into "+UploadTable+" values ("+row[0]+","+nullcheckstr(row[1])+","+nullcheckint(row[2])+","+nullcheckint(row[3])+","+nullcheckint(row[4])+","+nullcheckint(row[5])+","+nullcheckint(row[6])+","+nullcheckint(row[7])+","+nullcheckint(row[8])+")")
        print "insert into "+UploadTable+" values ("+str(row[0])+","+nullcheckstr(row[1])+","+nullcheckint(row[2])+","+nullcheckint(row[3])+","+nullcheckint(row[4])+","+nullcheckint(row[5])+","+nullcheckint(row[6])+","+nullcheckint(row[7])+","+nullcheckint(row[8])+")"
        i = i + 1
        print 'inserted ' + str(i) + ' rows'
    cnxn.commit()

row[0]是日期

nullcheckint/nullcheckstr:检查行是否为空

2 个答案:

答案 0 :(得分:0)

with open(UploadFile, "r") as uploadData:

    i=0
    flag=0
    formatter_string = "%d/%m/%y"
    d=[]
    for row in reader:
        if(flag==0):
            flag=flag+1
        else:
            datetime_object = datetime.strptime(row[0], formatter_string)
            row[0] = datetime_object.date()

        temp=[]
        for val,i in enumerate(row):
            if val==0:
                temp.append(str(row[0]))
            elif val == 1:
                temp.append(nullcheckstr(row[1]))
            else:
                temp.append(nullcheckint(row[1]))
        d.append(temp)

    for row in d:
        cursor.execute("insert into "+UploadTable+" values(?,?,?,?,?,?,?,?)",row)

        print 'inserted rows'


    cnxn.commit

答案 1 :(得分:0)

尝试使用此代码。它更清洁,更容易调试。在不知道您的输入文件是什么样的情况下,我必须假设该错误存在于您的混乱代码中。

一些错误/不一致:

  • 您永远不会使用uploadData
  • 您永远不会声明reader

with open(UploadFile, "r") as uploadData:
    i = 0

    # Since this is just a flag, use True/False
    flag = False
    formatter_string = "%d/%m/%y"
    for row in reader:
       if not flag:
            flag = True
       else:
            datetime_object = datetime.strptime(row[0], formatter_string)

            # Format each section of the row
            row[0] = datetime_object.date()
            row[1] = nullcheckstr(row[1])
            row[2:] = list(map(nullcheckint, row[2:]))

        # Use `str.format` to make this statement MUCH cleaner
        sql = "insert into {} values ({})".format(UploadTable, ','.join(row))
        cursor.execute(sql)

        i = i + 1

    print 'inserted {} rows'.format(str(i))
    cnxn.commit()