import psycopg2
try:
conn = psycopg2.connect("dbname='myDB' user='postgres' host='localhost' password='t@ida1234'")
cur = conn.cursor()
cur.execute("insert into test (name) values ('bert')")
# Close communication with the database
cur.close()
conn.close()
except:
print "I am unable to connect to the database"
但會發現,資料庫啥也沒有!!!!!
少寫了最重要的一行,這一行很重要,在所有資料插入完畢後,一定要寫這一行。
conn.commit()
使剛才新增的資料生效。
完整程式碼如下:
import psycopg2
try:
conn = psycopg2.connect("dbname='myDB' user='postgres' host='localhost' password='t@ida1234'")
cur = conn.cursor()
cur.execute("insert into test (name) values ('bert')")
conn.commit()
# Close communication with the database
cur.close()
conn.close()
except:
print "I am unable to connect to the database"
執行結果
沒有留言:
張貼留言