1

Having trouble creating geom columns and inserting geometry lat lng values into postgres table

  1. Is my syntax correct in creating the point geometry fields? st_makepoint is the point constructor. when I create the column should I be using that?
  2. or should I be using the st_makepoint when inserting into the column?

*python 2.7

conn = psycopg2.connect("connected")
cur.execute('''CREATE TABLE example(pgeom geometry(POINT, 4326),
         dgeom geometry(POINT, 4326));''')
for x in csvfile:
    extracting info...
    1geom = lng1+lat1 #int values
    2geom = lng2+lng2 #int values
    query = '''insert into example(geom1, geom2) values (%s,%s);'''
    data = (1geom, 2geom)
    cur.execute(query, data)
    conn.commit()
  • 1
    I think you should expand your code snippet to show where you set cur. – PolyGeo May 13 '16 at 5:02
  • st_makepoint is the point constructor I believe – ziggy May 13 '16 at 5:07
2

Read your CSV file and create a vars_list list of tuples to insert. Reading the CSV file is off topic, but it should have a structure something like this:

vars_list = [
    (lng1, lat1, lng2, lat2),  # first record
    (lng1, lat1, lng2, lat2),  # second
    ...
]

Then insert them all at once with executemany, like this:

sql = '''\
INSERT INTO example(pickup_geom, dropoff_geom)
VALUES(ST_SetSRID(ST_MakePoint(%s, %s), 4326), ST_SetSRID(ST_MakePoint(%s, %s), 4326));
'''
curs.executemany(sql, vars_list)
conn.commit()

Or if you want to individually insert records:

for vars in vars_list:
    curs.execute(sql, vars)
    conn.commit()
  • I have thousands of records, should I still use the executemany function? – ziggy May 13 '16 at 5:28
  • I'd guess executemany is faster, although you could do a test to see. – Mike T May 13 '16 at 6:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.