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

  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值