在python中使用insert查询来获取postgresql

时间:2015-12-16 05:40:18

标签: python postgresql python-2.7 python-3.x

我想使用python将值插入数据库,但它失败了。这是我的代码:

 try:
     cur.execute("""INSERT INTO tb_distance (objek1, objek2, distance) VALUES ('%s','%s','%d')""", (data[i].jenis, data[k].jenis, distance))
     conn.commit()
 except:
     conn.rollback()
     print 'cannot insert into database'

2 个答案:

答案 0 :(得分:1)

谢谢,我解决了我的问题,我在值列表之前将(,)替换为(%)。这是我的代码并运行良好:

cur.execute("""INSERT INTO tb_distance (objek1, objek2, distance) VALUES ('%s','%s','%f')""" % (data[i].jenis, data[k].jenis, distance))

答案 1 :(得分:0)

删除占位符周围的引号('%s' - > %s'%d' - > %d):

cur.execute(
    "INSERT INTO tb_distance (objek1, objek2, distance) VALUES (%s, %s, %d)",
    (data[i].jenis, data[k].jenis, distance)
)