I am having trouble inserting point values into my Postgresql database. I have enabled the postgis extension and set the column to type geometry(Point,4326). I have some data that I want to store in my database, this data can have NULL values in this column. The following SQL script works when there are no NULL values:
INSERT INTO tweets(id, content, location, retweet_count, favorite_count, happened_at, author_id, country_id)
VALUES(%s, %s, '%s', %s, %s, %s, %s, %s) RETURNING id;
The third value, location, is the point type. Is there a surefire way to guarantee both NULL and point values will be recorded?
Update: After finding a piece of code online I updated my code accordingly:
if location is not None:
sql = """INSERT INTO tweets(id, content, location, retweet_count, favorite_count, happened_at, author_id, country_id)
VALUES(%s, %s, ST_SetSRID(ST_MakePoint(%s, %s),4326), %s, %s, %s, %s, %s) RETURNING id;"""
data = (tweet_id, content, location[0], location[1], retweet_count, favorite_count, happened_at, author_id, country_id,)
else:
sql = """INSERT INTO tweets(id, content, location, retweet_count, favorite_count, happened_at, author_id, country_id)
VALUES(%s, %s, %s, %s, %s, %s, %s, %s) RETURNING id;"""
data = (tweet_id, content, location, retweet_count, favorite_count, happened_at, author_id, country_id,)
After which I can select date from the database like this:
select * from tweets where location = 'POINT(3.576 6.6128)'::geography;
1 Answer 1
If the column location isn't set as not null, there shouldn't be a problem to add null values.
CREATE TEMPORARY TABLE t (geom geometry(point,4326));
INSERT INTO t VALUES (null),('SRID=4326;POINT(1 2)');
SELECT * FROM t;
geom
----------------------------------------------------
0101000020E6100000000000000000F03F0000000000000040
(2 Zeilen)
Keep in mind that an empty string '' isn't a valid value! Insert either a valid geometry or null.
5 Comments
parse error - invalid geometry LINE 3: xyz', 'NULL', 0, 1, 'Thu Aug 06 06:59:54... ^ HINT: "NU" <-- parse error at position 2 within geometry'NULL' with single quotes. It should be NULL WITHOUT quotes :-)
not null?not null.