python3 操作mysql

需要安装PyMySQL

PyMySQL是python3.x连接mysql服务的一个库, python2中使用mysqldb

安装PyMySQL

$ pip install PyMySQL

实现python操作mysql

import pymysql

class db_operation:

    def __init__(self, user_name, password, db_name):
        #username 表示用户名, password 表示密码, db_name表示要连接的数据库名称
        self.conn = self.get_conn(user_name, password, db_name)
        self.cursor = self.conn.cursor()

    @classmethod
    def get_conn(cls, user_name, password, db_name):
        #获得连接游标;
        conn = pymysql.connect("localhost", user_name, password, db_name)
        return conn

    def execute_sql(self, sql, args=None):
        #执行sql语句返回受影响的行数;
        try:
            num = self.cursor.execute(sql, args)
            self.conn.commit()
            return num
        except Exception as e:
            print(e)
            raise e

    def select_sql(self, sql, args=None):
        #执行sql语句,返回查询到的结果集合;
        try:
            self.cursor.execute(sql, args)
            res = self.cursor.fetchall()
            return res
        except Exception as e:
            print(e)
            raise e

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值