Insert Python NumPy array into PostgreSQL database

时间:2018-12-19 11:31:00

标签: python postgresql numpy sql-insert psycopg2

How do I insert a large array of coordinates (x,y) into a postgresSQL table? I don't want to use a for loop. It is a raster with 3601x3601 pixels.

import numpy as np
import psycopg2


# Data example:
east = np.linspace(-180.0,180.0,num=10)
north = np.linspace(-90.0,90.0,num=10)
coor = np.vstack([east, north])

conn = psycopg2.connect("dbname='postgres' user='dbuser' host='localhost' password='dbpass'")
cur = conn.cursor()
cur.execute("DROP TABLE IF EXISTS foobar;")
cur.execute("CREATE TABLE foobar (coordinate   point);")

# Working for an coordinate example:
cur.execute("INSERT INTO foobar VALUES (('12.56,56.43'));")

# Working for 1st coordinate in coor:
tmp = ','.join(str(e) for e in coor[:,0])
cur.execute('INSERT INTO foobar VALUES (point(' + tmp + '));')

# NOT WORKING!!!
# Insert all points in one go:
# cur.execute('INSERT INTO foobar VALUES (coor);')

conn.commit()

2 个答案:

答案 0 :(得分:2)

使用功能execute_values(),您可以使用单个SQL语句插入多行。您应该使用以下格式为该函数准备数据:

CREATE TABLE "INS_RAZNO"."ZAPOSLENICI_TEST"(
    PREZIME varchar(15),
    IME varchar(15),
    ODJEL varchar(15), 
    SLOŽENOST_POSLA int, 
    STAROST int, 
    MJESEČNI_OD int
);

代码:

[['(-180.0, -90.0)'],
 ['(-140.0, -70.0)'],
 ['(-100.0, -50.0)'],
 ['(-60.0, -30.0)'],
 ['(-20.0, -10.0)'],
 ['(20.0, 10.0)'],
 ['(60.0, 30.0)'],
 ['(100.0, 50.0)'],
 ['(140.0, 70.0)'],
 ['(180.0, 90.0)']]

另请参阅this answer.

答案 1 :(得分:1)

您可以使用cur.executemanypsycopg2.extras.execute_values一次插入许多记录。这是适合使用execute_values的示例:

import psycopg2.extras
values = map(lambda a: ['{},{}'.format(a[0],a[1])], np.column_stack((east, north)))
psycopg2.extras.execute_values(cur, "INSERT INTO foobar (coordinate) VALUES %s", values)