Python学习笔记(三) 数据库连接

796 阅读4分钟

Python学习笔记(三) 数据库连接

数据库连接

先需要安装依赖 pip install PyMySQL ,如果你还未设置python依赖下载的全局镜像,请跳转至

测试数据连接使用


import pymysql

# 创建数据库连接 
db = pymysql.connect("192.168.10.112","xiongchao","xiongchao","xiongchao")

# 使用cursor()方法创建一个游标对象
cursor = db.cursor()

# 使用excuse方法执行查询数据库版本

# execute 中可以执行 crud 基本操作的语句
try:
    cursor.execute("select * from user")
    # 获取一条数据
    data = cursor.fetchall()
    cursor.fetchone()
    print(data)

    for e in data:
        id = e[0]
        name = e[1]

        print('id :{},name:{}'.format(id,name))
except expression as identifier:
    print("Error: unable to find data from db")

db.close()

工具类封装类似于java中的dao

文件此处命名为db.py,测试的类放在与之相同路径

import pymysql
class db_utils:

    def __init__(self):
        self.ip = '192.168.10.112'
        self.username = 'xiongchao'
        self.password =  'xiongchao'
        self.database ='xiongchao'
        self.cursor = ''
        self.db = ''

""" 创建数据库连接 """
    def create_db(self):
        try:
            db = pymysql.connect(self.ip,self.username,self.password,self.database)
            self.db = db
            cursor = db.cursor()
            self.cursor = cursor
        except :
            print("Error: connect to {} timeout ,please check config, and try agin".format(self.ip))
        """ 单个查询 """
    def find_one(self,sql):
        try:
            self.cursor.execute(sql)
            data = self.cursor.fetchone()
            return data
        except :
            print("Error: no data find ")
         self.db.close()
    """ 多个查询 """
    def find_all(self,sql):
        try:
            self.cursor.execute(sql)
            data = self.cursor.fetchall()
            res = []
            if len(data) > 0 :
                for item in data :
                    res.append({'id': item[0],'name':item[1]})

            return res
        except:
            print('Error no data find')
         self.db.close()

    def update(self,sql):
        try:
            self.cursor.execute(sql)
            # 数据提交
            self.db.commit()
        except:
            # 错误的时候 回滚
            self.db.rollback()
        self.db.close()
   


# 测试 
""" if __name__ == "__main__":
    test = db_utils()
    cursor = test.create_db()
    data = test.find_one("select * from user ")
    #  返回的是元祖类型 取值通过下标的方式取
    print(type(data))
    print(data[0],data[1]) """

测试

# 引用自己封装的包
import db

if __name__ == "__main__":
    # 对象实例化
    test = db.db_utils()
    test.create_db()

    data = test.find_all("select * from user")
    #  将元祖类型转换成 字典形式
    print(data)
    test.close_cont()


剩下其它的修改删除用法基本相同