首先需要psycopg2
剩下的直接看代码:
import psycopg2class connect: def __init__(self): self.con = psycopg2.connect(database=’XXX’, user=’XXXX’, password=’XXXXXX’, host=’127.0.0.1′, port=5432) self.cursor = self.con.cursor() def getall(self, sql): self.cursor.execute(sql) return self.cursor.fetchall() def execute(self, sql): self.cursor.execute(sql) self.con.commit() def create_table(self, sql): self.cursor.execute(sql) def close(self): self.con.close()conn = connect()conn.execute(“create table test_2(id int,name varchar(20))”)conn.execute(“insert into test_2 values(1,’1g’)”)conn.execute(“insert into test_2 values(2,’2g’)”)print(conn.getall(“select * from test_2”))