Python与数据库连接

新建表boss

create table 创建表
在这里插入图片描述

Code

import pymysql

con = pymysql.connect(host='localhost',\
                      user='root',\
                      password='',\
                      port=3306,\
                      db='business')
cursor=con.cursor()
cursor.execute('''create table if not exists boss(
                    id int auto_increment primary key,
                    name varchar(20)not null,
                    salary int not null)''')

添加数据

inser into添加数据
con.commit() #提交
在这里插入图片描述

Code

cursor.execute('''
        insert into boss(name,salary)
        values('Jack',91),('Harden',1300),('Pony',200)
        ''')
con.commit()#提交

删除数据

delete from删除数据
在这里插入图片描述

Code

# 删除
cursor.execute('delete from boss where salary < 100')
con.commit()

更新

update boss set salary = 2000 where name = 'Pony'
在这里插入图片描述

# 更新
cursor.execute("update boss set salary = 2000 where name = 'Pony'")
con.commit()

数据库封装

报错:AttributeError: 'UsingMysql' object has no attribute '_log_time'
解决方法:https://www.php1.cn/detail/ChengGongJieJue__4c4b7b31.html

from timeit import default_timer

import pymysql

host='losthost'
port=3306
db='business'
user='root'
password=''

# 类似参数化(PyMySQL操作数据库)
def get_connection():
    conn = pymysql.connect(host=host,port=port,db=db,user=user,password=password)
    return conn


# 使用with优化代码


class UsingMysql(object):
    def __init__(self,commit=True,log_time=True,log_label='总用时'):
        '''
        paramcommit是否在最后提交事务(设置为False的时候方便单元测试)
        paramlog_time:是否打印程序运行总时间
        paramlog_label:自定义log的文字
        '''
        self.log_time = log_time
        self.commit = commit
        self._log_label = log_label

    def __enter__(self):  # 如果需要记录时间
        if self._log_time is True:
            self._start = default_timer()
            # 在进入的时候自动获取连接和cursor
            conn = get_connection()
        cursor= conn.cursor(pymysql.cursors.DictCursor)
        conn.autocommit=False
        self._conn = conn
        self._cursor= cursor
        return self

    # 资源释放
    def __exit__(self, *exc_info):
        # 提交事务
        if self._commit:
            self._conn.commit()
        #在退出的时候自动关闭连接和cursor
        self._cursor.close()
        self._conn.close()

        if self._log_time is True:
            diff = default_timer() - self._start
            print('- % s: %.6f秒 ' % (self._log_label, diff))   #总用时

    # 不必要的封装
    # 一系列封装的业务方法
    #返回count
    # def get_count(self,sql,params=None,count_key='count(id)'):
    #     self.cursor.execute(sql.params)
    #     data = self.cursor.fetchone()
    #     if not data:
    #         return 0
    #     return data[count_key]

    # def fetch_one(self, sql,params=None):

if __name__ == '__main__':
    with UsingMysql(log_time=True) as um:
        um._cursor.execute('select count(id) as total from boss')
        data = um._cursor.fetchone()  # 2
        print("当前记录数量:%d" % data['total'])

预期结果:

在这里插入图片描述

参考文章:https://blog.csdn.net/BJ1599449/article/details/117026500

相关推荐

  1. python连接数据库

    2024-04-23 10:08:01       35 阅读
  2. python连接Mysql数据库

    2024-04-23 10:08:01       32 阅读
  3. python连接数据库

    2024-04-23 10:08:01       30 阅读
  4. PythonC#之间的双向管道连接-发送数据

    2024-04-23 10:08:01       30 阅读
  5. python连接mysql数据库步骤

    2024-04-23 10:08:01       35 阅读
  6. Python连接数据库进行数据查询

    2024-04-23 10:08:01       28 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-23 10:08:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-23 10:08:01       101 阅读
  3. 在Django里面运行非项目文件

    2024-04-23 10:08:01       82 阅读
  4. Python语言-面向对象

    2024-04-23 10:08:01       91 阅读

热门阅读

  1. GPT-SoVITS声音训练报错ZeroDivisionError: division by zero

    2024-04-23 10:08:01       32 阅读
  2. 分布式与微服务的区别

    2024-04-23 10:08:01       41 阅读
  3. python-读写文本数据

    2024-04-23 10:08:01       34 阅读
  4. 从零手写 tomcat

    2024-04-23 10:08:01       55 阅读
  5. STM32 ST-LINK

    2024-04-23 10:08:01       78 阅读
  6. QML与C++交互

    2024-04-23 10:08:01       38 阅读
  7. 每日一题:Spring MVC 的执行流程是什么❓

    2024-04-23 10:08:01       41 阅读
  8. 【LeetCode热题100】【图论】课程表

    2024-04-23 10:08:01       149 阅读