Python dbsql postgres sql
## 创建数据库
pip install psycopg2
docker pull postgres:10
docker run -d --name=postgres -e POSTGRES_PASSWORD=root -p 5432:5432 postgres:10
docker exec -it postgres bash
su postgres
psql -U postgres -W
CREATE TABLE DEPARTMENT(
ID INT PRIMARY KEY NOT NULL,
PAGE_INDEX INT NOT NULL,
PAGE_SIZE INT NOT NULL
);
python
import psycopg2
conn = psycopg2.connect(database="ru", user="postgres", password="root", host="47.93.224.221", port="55432")
cur = conn.cursor()
# cur.execute("INSERT INTO DEPARTMENT (ID,PAGE_INDEX,PAGE_SIZE) \
# VALUES (10 ,1, 2)");
# conn.commit()
cur.execute("SELECT id, page_index, page_size from DEPARTMENT")
rows = cur.fetchall()
for row in rows:
print("ID = ", row[0])
print("page_index = ", row[1])
print("page_size = ", row[2])
conn.commit()
print("Opened database successfully")
import psycopg2
class DBUtils():
def __init__(self):
self.conn = psycopg2.connect(database="ru", user="postgres", password="root", host="47.93.224.221", port="55432")
self.cursor = self.conn.cursor()
def dbSelect(self,sql):
print("------------------------------------")
print(sql)
resultList = []
self.cursor.execute(sql)
result = self.cursor.fetchall()
columns = self.cursor.description
for val in result:
tempDict = {}
for cloNum in range(len(columns)):
tempDict[str(columns[cloNum][0])] = val[cloNum]
resultList.append(tempDict)
print("---------------------打印查询结果----------------------")
print(resultList)
# self.dbClose()
return resultList
def dbExcute(self, sql):
print("execute sql")
print(sql)
self.cursor.execute(sql)
self.dbClose()
def dbClose(self):
self.conn.commit()
self.cursor.close()
self.conn.close()
def main():
a = DBUtils()
resutl= a.dbSelect("SELECT id, page_index, page_size from DEPARTMENT")
print(resutl)
# a.dbSelect("SELECT id, page_index, page_size from DEPARTMENT")
if __name__ == '__main__':
main()
: