python 连接mysql及读取数据

python 连接mysql操作类

查了好长时间,从网上居然没找到python操作mysql的类,那就自己写一个吧,方便以后直接用

1.准备

使用pip 安装pymysql包

pip install pymysql

python版本为python3

2.连接mysql进行增删改查的代码如下

class MysqlConn:

    def __init__(self, dbconfig):
        try:
            self.conn = pymysql.connect(host=dbconfig['host'],
                                        port=dbconfig['port'],
                                        user=dbconfig['user'],
                                        passwd=dbconfig['passwd'],
                                        db=dbconfig['db'],
                                        charset=dbconfig['charset'])
            self.cur = self.conn.cursor(pymysql.cursors.DictCursor)
        except pymysql.Error as e:
            print("Mysql Error %d: %s" % (e.args[0], e.args[1]))


    def query(self, sql):
        """
        执行一个sql
        调用方式 query(sql)
        :param sql: 表名
        :return:
        """
        try:
            n = self.cur.execute(sql)
            return n
        except pymysql.Error as e:
            print("Mysql Error:%s\nSQL:%s" % (e, sql))

    def query_row(self, sql):
        """
        查询一行数据,返回字典格式的数据
        调用方式 query_row(sql)
        :param sql: 查询sql
        :return: {'key1':value1,'key2':value2}
        """
        self.cur = self.conn.cursor(pymysql.cursors.DictCursor)
        self.query(sql)
        result = self.cur.fetchone()

        return result

    def query_all(self, sql):
        """
        查询所有数据,返回列表嵌套字典格式的数据
        调用方式 query_all(sql)
        :param sql: 查询sql
        :return: [{'key1':value1,'key2':value2},{'key1':value1,'key2':value2}]
        """
        self.cur.execute(sql)
        result = self.cur.fetchall()
        return result

    def insert_dict(self, p_table_name, p_data, replace=False):
        """
        向指定表中插入一条数据
        调用方式 insert('table','{key1:val1,key2:val2}',False)
        :param p_table_name: 表名
        :param p_data: 表数据 字典格式{'field1':'val','field2':'val'}
        :param replace: 是否替换
        :return: 插入表的最后新增id
        """
        p_data_copy = p_data.copy()
        formatKeys = ''
        formatValues = ''
        for pkey,pval in p_data_copy.items():
            formatValues += "'" + str(pval) + "',"
            formatKeys += "`%s`," % (pkey)
        key = formatKeys.rstrip(',')
        value = formatValues.rstrip(',')
        if replace:
            insert = "REPLACE"
        else:
            insert = "INSERT"
        real_sql = insert + " INTO " + p_table_name + " (" + key + ") VALUES (" + value + ")"
        self.query(real_sql)
        self.commit()

        return self.cur.lastrowid

    def update_dict(self, p_table_name, p_data, where):
        '''
        更新数据
        使用方式 update('user_label_list',{'label_desc':'aaaa'},"id=1")
        :param p_table_name: 表名
        :param p_data: 要更新的列 字典格式 {'key1':'val1','key2':'val2'}
        :param where: where条件
        :return: 修改的记录条数
        '''
        p_data_copy = p_data.copy()
        for key in p_data_copy:
            p_data_copy[key] = "`" + key + "`='" + str(p_data_copy[key]) + "'"
        value = ','.join(p_data_copy.values())

        real_sql = "UPDATE " + p_table_name + " SET " + value + " WHERE " + where

        self.query(real_sql)
        self.commit()

        return self.cur.rowcount

    def delete(self, sql):
        """
        删除数据
        :param sql:
        :return:
        """
        self.query(sql)
        self.commit()
        return self.cur.rowcount

    def commit(self):
        self.conn.commit()

    def close(self):
        self.cur.close()
        self.conn.close()

3.实例化类

实例化MysqlConn这个类,然后就可以进行相关数据的操作了

config ={
    'host':'localhost',
    'port':3306,
    'user':'root',
    'passwd' : '******',
    'db' : 'test',
    'charset' : 'utf8'
}
mysql_db = MysqlConn(config)

4.增删改查操作

# 查一条数据
user_info = mysql_db.query_row("select id,user_name from user_info")
print(user_info)

# 查全部数据
user_all = mysql_db.query_all("select id,user_name,area from user_info")
print(user_all)

# 新增一条数据
insert_data = {
    'user_name' : 'test',
    'mobile' : '13000000000',
    'remark' : 'test user',
    'add_time' : '2023-03-10 14:40:40',
    'source' : 'gaoguang',
    'area' : '北京'
}
incid = mysql_db.insert_dict("user_info",insert_data)
print(incid)

# 修改某条数据
update_data = {
    'mobile' : '13100000001'
}
where_str = "id=9"
rowid = mysql_db.update_dict("user_info",update_data,where_str)
print(rowid)

# 删除某条数据
sql = "delete from user_info where id=9"
res = mysql_db.delete(sql)
print(res)

你可能感兴趣的:(python,mysql,python,mysql,数据库)