2014-11-21 63 views
2

我是一個Python學習者,Python和PostgreSQL - GeomFromText

我試圖插入幾何記錄到PostgreSQL。

如果我嘗試沒有幾何列的查詢,它工作正常,所有數據插入成功。

cur.execute("INSERT INTO taxi (userid,carNum) SELECT '"+str(msg['UserID'])+"',"+str(msg['CarNumber'])) 

一旦我嘗試添加幾何記錄,什麼都不會發生!執行結束時沒有錯誤,但沒有插入到數據庫中。

cur.execute("INSERT INTO taxi (position,userid,carNum) SELECT GeomFromText('POINT("+str(float(msg['longitude']))+" "+str(float(msg['latitude']))+")',4326),'"+str(msg['UserID'])+"',"+str(msg['CarNumber'])) 

想不出什麼,我在這裏失蹤

回答

1

您需要將數據提交到數據庫。

檢查psycopg2的文檔http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries

按照這些步驟

>>> import psycopg2 

# Connect to an existing database 
>>> conn = psycopg2.connect("dbname=test user=postgres") 

# Open a cursor to perform database operations 
>>> cur = conn.cursor() 

# Execute a command: this creates a new table 
>>> cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);") 

# Pass data to fill a query placeholders and let Psycopg perform 
# the correct conversion (no more SQL injections!) 
>>> cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)", 
...  (100, "abc'def")) 

# Query the database and obtain data as Python objects 
>>> cur.execute("SELECT * FROM test;") 
>>> cur.fetchone() 
(1, 100, "abc'def") 

# Make the changes to the database persistent 
>>> conn.commit() 

# Close communication with the database 
>>> cur.close() 
>>> conn.close()