我使用Python将数据从Mysql数据库移动到PostgresDB。我的代码如下-
conn = psycopg2.connect("dbname='aaa' user='aaa' host='localhost' password='aaa' ")
curp = conn.cursor()
db = MySQLdb.connect(host="127.0.0.1", user="root", passwd="root" , unix_socket='/var/mysql/mysql.sock', port=3306 )
cur.execute('select * from aaa_pledge')
list = cur.fetchall()
for l in list:
print l
for i in range(len(l)):
print i, l[i]
qry = "insert into aaa_pledge values ('%s','%s','%s','%s',%s,%s,'%s',%s,%s,%s,%s,'%s')" %( l[0], l[1], l[2], l[3], l[4], l[5], l[6], str(l[7]) , l[8], l[9], l[10], l[11] )
print qry
res = curp.execute( qry)
print res
curp.execute( "commit")
curp.close()
cur.execute( "commit")
cur.close()
代码对于有效日期运行良好,执行如下-
^{pr2}$但是当源代码有null时,在元组中我们得到一个None
('500055', 'NEERAJ SINGAL', datetime.date(2014, 11, 26), 'NEERAJ SINGAL', Decimal('57394244.00'), Decimal('25.3300000'), 'INVOCATION', ***None,*** Decimal('0E-7'), Decimal('0E-7'), Decimal('0E-7'), '-')
0 500055
1 NEERAJ SINGAL
2 2014-11-26
3 NEERAJ SINGAL
4 57394244.00
5 25.3300000
6 INVOCATION
***7 None***
8 0E-7
9 0E-7
10 0E-7
11 -
insert into aaa_pledge values ('500055','NEERAJ SINGAL','2014-11-26','NEERAJ SINGAL',57394244.00,25.3300000,'INVOCATION','None',0E-7,0E-7,0E-7,'-')
Traceback (most recent call last):
File "pransfer_data.py", line 27, in <module>
res = curp.execute( qry)
psycopg2.DataError: invalid input syntax for type date: "None"
LINE 1: ...EERAJ SINGAL',57394244.00,25.3300000,'INVOCATION','None',0E-...
我读了一些关于使用%s而不是'%s'的说明,以及关于使用str(l[7])的说明。但是,在每种情况下,如果代码在有效日期内运行良好,则对于无效日期则失败,反之亦然。对于其他整数值,我也要面对这个问题。在
有办法吗
PS-我有很多日期和数字列,这是需要的。我不能为每个列都做if-then-else。在
谢谢, 曼尼什语
你需要一个NULLIF和一个CAST:
您需要做的是调用psycopg2的
cursor.execute
方法的parameterized form在查询中传递(使用%s
占位符,,而不立即对其进行插值)作为execute
第一个参数的字符串,然后传入一个包含参数值的元组作为第二个参数。比如:考虑以下愚蠢的测试表:
^{pr2}$使用以下Python代码执行插入:
然后在数据库中得到以下结果:
请注意,当您使用参数化版本时,
None
将作为空值正确插入到PostgreSQL中。在相关问题 更多 >
编程相关推荐