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

猜你喜欢

转载自blog.csdn.net/wangzhuo0978/article/details/79932171
今日推荐