python mysql处理

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()

:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值