Psycopg2 copy_from抛出DataError:整数的输入语法无效

时间:2016-02-08 17:32:08

标签: postgresql python-2.7 psycopg2

我有一个包含一些整数列的表。我正在使用psycopg2的copy_from

...

<form action="" method="post">  
    <select name="addresstype[]" id="multiselectfrom" onchange='this.form.submit();' size="9" style="width:110px; text-align:center;">
        <option style="<?php if ($AddType == 'Claimant') { echo'background-color:#9AD3F1 !important;'; } ?>" value="Claimant"><?php echo $LANG_Claims_Claimant; ?></option>
        <option style="<?php if ($AddType == 'Vehicle') { echo'background-color:#9AD3F1 !important;'; } ?>" value="Vehicle"><?php echo $LANG_Claims_Vehicle; ?></option>
        <option style="<?php if ($AddType == 'Repairer') { echo'background-color:#9AD3F1 !important;'; } ?>" value="Repairer"><?php echo $LANG_Claims_Repairer; ?></option>
        <option style="<?php if ($AddType == 'Insurer') { echo'background-color:#9AD3F1 !important;'; } ?>" value="Insurer"><?php echo $LANG_Claims_Insurer; ?></option>
        <option style="<?php if ($AddType == 'Fleet') { echo'background-color:#9AD3F1 !important;'; } ?>" value="Fleet"><?php echo $LANG_Claims_Fleet; ?></option>
    </select>
</form>

...

<?php
    if (isset($_POST['addresstype']))
    { 
        foreach ($_POST['addresstype'] as $addresstype) {
            $addresstype2 = $addresstype;
        }
        echo "<script>window.location='claims.php?claimID=" . $claim . "&claimTab=Addresses&AddressType=" . $addresstype2 . "'</script>";
    }
?>

错误说它希望第8列是整数而不是字符串。但是,Python的write方法只能读取文件的字符串。那么,如果您的文件只能包含整数的字符表示(例如str(your_number)),那么如何将一个充满数字字符串表示的文件导入到postgres表中,并使用期望整数的列。

你要么必须以整数格式将数字写入文件(Python的写入方法不允许),要么psycopg2应该足够聪明地进行转换,作为copy_from过程的一部分,显然它不是。任何想法都表示赞赏。

1 个答案:

答案 0 :(得分:1)

我最终使用了copy_expert命令。请注意,在Windows上,您必须设置文件的权限。这篇文章非常有用setting permission

with open(the_file, 'r') as f:            
        sql_copy_statement = "copy {table} FROM '"'{from_file}'"' DELIMITER '"'{deli}'"' {file_type} HEADER;".format(table = the_table,
                                                                                                                     from_file = the_file,
                                                                                                                     deli = the_delimiter,
                                                                                                                     file_type = the_file_type                                                                                                                                         
                                                                                                                    )
        print sql_copy_statement
        cur.copy_expert(sql_copy_statement, f)
        conn.commit()
相关问题