天天看點

再繼續上次話題,這次要做的是用python操作postgresql

首先安裝psycopg2

import psycopg2

conn=psycopg2.connect(database="postgres",user="postgres",password="1234",host="127.0.0.1",port="5432")

cur = conn.cursor()

cur.execute("CREATE TABLE student1(id double precision,name varchar,sex varchar);")

#插入資料

cur.execute("INSERT INTO student(id,name,sex)VALUES(%s,%s,%s)",(1,'Aspirin','M'))

cur.execute("INSERT INTO student(id,name,sex)VALUES(%s,%s,%s)",(2,'Taxol','F'))

cur.execute("INSERT INTO student(id,name,sex)VALUES(%s,%s,%s)",(3,'Dixheral','M'))

cur.execute("SELECT * from student")

rows = cur.fetchall()

conn.commit()

cur.close()

conn.close()

這裡有幾個注意的細節,之前一直使用numeric的資料格式,最後導出的時候産生一些問題:

再繼續上次話題,這次要做的是用python操作postgresql

會出現decimal這個詞,影響使用,最後改為double precision。。。另外

需要:

conn.commit()

cur.close()

conn.close()

以後重新打開pgadmin才能看到建立的表,如果是已經有的表,那就cur

(select * from combin1)

cur = conn.cursor()

cur.execute("SELECT * from combin1")

rows = cur.fetchall()

rows[1][0]

其他使用暫時沒有親自實驗過,暫時認為可以順利的繼續進行。