Python 日期 - 将 None 转换为 Null

标签 python mysql postgresql psycopg2

我正在使用 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()

代码在有效日期 下运行良好,执行如下 -

('500055', 'NEERAJ SINGAL', datetime.date(2014, 12, 4), 'NEERAJ SINGAL', Decimal('57221712.00'), Decimal('25.2600000'), 'INVOCATION', datetime.date(2014, 12, 4), Decimal('0E-7'), Decimal('0E-7'), Decimal('0E-7'), '-')
0 500055
1 NEERAJ SINGAL
2 2014-12-04
3 NEERAJ SINGAL
4 57221712.00
5 25.2600000
6 INVOCATION
***7 2014-12-04***
8 0E-7
9 0E-7
10 0E-7
11 -
insert into aaa_pledge values ('500055','NEERAJ SINGAL','2014-12-04','NEERAJ SINGAL',57221712.00,25.2600000,'INVOCATION','2014-12-04',0E-7,0E-7,0E-7,'-')

但是当源有空值时,在元组中我们得到一个 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]) 的注释。但是,在每种情况下,如果代码在有效日期运行良好,则在无效日期运行失败,反之亦然。对于其他整数值,我也将面临这个问题。

有没有办法

  1. 自动将 None 转换为 null 和
  2. 根据需要将有效日期的“%s”更改为无效日期的 %s。

PS - 我有很多日期和数字列,这是必需的。我将无法为每一列执行 if then else。

谢谢, 马尼什

最佳答案

您需要做的是调用 parameterized form psycopg2 的 cursor.execute 方法 - 传入查询(使用 %s 占位符,没有立即插入)作为字符串execute 的第一个参数,然后传入一个包含您的参数值的元组作为第二个参数。像这样的东西:

insertQuery = 'INSERT INTO foo VALUES (%s, %s, %s)'
cursor.execute(insertQuery, (1, 'Alice', datetime.date(2014, 12, 4)))

考虑以下愚蠢的测试表:

rchang=> \d foo
                Table "public.foo"
 Column |            Type             | Modifiers
--------+-----------------------------+-----------
 id     | integer                     |
 name   | text                        |
 ts     | timestamp without time zone |

使用以下 Python 代码执行插入:

insertQuery = 'INSERT INTO foo VALUES (%s, %s, %s)'

conn = psycopg2.connect(connString)
cursor = conn.cursor()

cursor.execute(insertQuery, (1, 'Alice', datetime.date(2014, 12, 4)))
cursor.execute(insertQuery, (2, 'Bob', None))

conn.commit()
conn.close()

然后我们在数据库中得到如下结果:

rchang=> select * from foo;
 id | name  |         ts      
----+-------+---------------------
  1 | Alice | 2014-12-04 00:00:00
  2 | Bob   |
(2 rows)

请注意,当您使用参数化版本时,None 会作为空值正确插入到 PostgreSQL 中。

关于Python 日期 - 将 None 转换为 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28603110/

相关文章:

python - Web API 和渲染模板,它们应该在同一个函数调用中吗?

php - 如何在 Codeigniter 中将 SQL 结果字符串转换为数组?

mysql - 在事件记录查询中转义两个反斜杠和撇号

python - 几个 .pyx 的 Cython setup.py

python - 退出python程序后调用bash脚本

python - 如何清理文本数据中的\xc2\xa0\xc2\xa0.....

mysql - 在mysql中使用多个连接时加快查询速度

sql - PostgreSQL select * 其中列包含数组值

json - 如何将 hylang s-表达式序列化为 PostgreSQL json/json-b?

postgresql - 如何通过两组连接记录查询连接表中的数据?