python 操作mysql类封装

# -*- coding: utf-8 -*-
import pymysql
import numpy as np
import pandas as pd
from sqlalchemy import create_engine


class MysqlOp():
    def __init__(self, host='127.0.0.1', user='root', passwd='123456', port=3306, db='test_db', charset='utf8'):

        self.host = host
        self.user = user
        self.passwd = passwd  # 密码
        self.port = port  # 端口,默认为3306
        self.db = db  # 数据库名称
        self.charset = charset  # 字符编码
        self.conn = pymysql.connect(host=self.host, user=self.user, passwd=self.passwd,
                                    port=self.port, db=self.db, charset=self.charset)
        self.cur = self.conn.cursor()
        # create_engine()初始化数据库连接时需要提供:'数据库类型+数据库驱动名称://用户名:密码@地址:端口号/数据库名'
        self.engine = create_engine('mysql+pymysql://{usr}:{paswd}@{host}:{port}/{db}'.format(usr=user, paswd=passwd,
                                                                                        host=host, port=port, db=db))
    def getCur(self):
        print('Get cur successfully!')
        return self.cur

    def creat_table(self, df=None, tbName=None, index=False):
        if df is None:
            raise ValueError('Your input df is None!')
        df.to_sql(tbName, self.engine, index=index)
        print('Create table {tbName} successfully!'.format(tbName=tbName))

    def write_table(self, tbName=None, df=None):
        if df is None:
            raise ValueError('Your input df is None!')
        df.to_sql(tbName, self.engine, schema=self.db, index=False, if_exists='append')
        print('Write table {tbName} successfully!'.format(tbName=tbName))

    def delete_table(self, tbName=None, conditon=None):
        # eg:condition='con=1,con=2'
        if conditon is not None:
            sql = """DELETE FROM {tbName} WHERE {con}""".format(tbName=tbName, con=conditon)
        else:
            sql = """DELETE FROM {tbName}""".format(tbName=tbName)
        self.cur.execute(sql)
        print('Delete data from table {tbName} successfully!'.format(tbName=tbName))

    def listTables(self):
        sql = """show tables"""  # SQL语句
        self.cur.execute(sql)  # 执行SQL语句
        data = self.cur.fetchall()  # 通过fetchall方法获得数据
        data = [t[0] for t in list(data)]
        print('Tables of database {db}: {tables}'.format(db=self.db, tables=data))
        return data

    def update_table(self, tbName=None, content=None, conditon=None):
        # eg:condition='con=1,con=2'
        # eg:content={field1=sth_new, field2=sth_new}
        content_new = """"""
        for k, v in content.items():
            if type(v) is str:
                content_new += """{k}='{v}',""".format(k=k, v=v)
            else:
                content_new += """{k}={v},""".format(k=k, v=v)
        sql = """UPDATE {tbName} SET {content} WHERE {con}""".format(tbName=tbName, content=content_new[:-1], con=conditon)
        print(sql)
        self.cur.execute(sql)
        print('Update table {tbName} successfully!'.format(tbName=tbName))

    def readTable(self, tbName=None, items='*'):  # eg: items='field1, field2'
        if tbName is None:
            raise ValueError("tbName is None!")
        sql = """select {items} from {tbName}""".format(items=items, tbName=tbName)
        self.cur.execute(sql)
        data = np.array(self.cur.fetchall())
        sql = """select COLUMN_NAME from information_schema.COLUMNS where table_name = '{tbName}'""".format(tbName=tbName)
        self.cur.execute(sql)
        cols = list(self.cur.fetchall())
        cols = [col[0] for col in cols]
        data = pd.DataFrame(data, columns=cols)
        print(data.head())
        print('Read table {tbName} successfully!'.format(tbName=tbName))
        return data

    def showTableInfo(self,tbName=None):
        if tbName is None:
            raise ValueError("tbName is None!")
        sql = """show create table {tbName}""".format(tbName=tbName)
        self.cur.execute(sql)
        data = self.cur.fetchall()
        for s in list(data[0]):
            if s == tbName:
                continue
            print(s)
        return list(data[0])

    def dropTable(self,tbName=None):
        if tbName is None:
            raise ValueError("tbName is None!")

        sql = """drop table if exists {tbName}""".format(tbName=tbName)
        self.cur.execute(sql)
        print('Drop table {tbName} successfully!'.format(tbName))

    def execSql(self, sql=None):
        if sql is None:
            return
        else:
            self.cur.execute(sql)
            print('Run sql:{sql} successfully!'.format(sql=sql))


if __name__ == '__main__':

    sqlhandle = MysqlOp(host='127.0.0.1', user='root', passwd='123456', port=3306, db='test_db')
    




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
对于Python MySQL封装,可以使用第三方库来实现。一个常用的库是`pymysql`,它提供了PythonMySQL数据库的交互功能。以下是一个简单的MySQL封装的示例代码: ```python import pymysql class MySQLWrapper: def __init__(self, host, user, password, database): self.host = host self.user = user self.password = password self.database = database self.connection = pymysql.connect(host=self.host, user=self.user, password=self.password, database=self.database) self.cursor = self.connection.cursor() def execute_query(self, query): self.cursor.execute(query) result = self.cursor.fetchall() return result def execute_update(self, query): self.cursor.execute(query) self.connection.commit() def close(self): self.cursor.close() self.connection.close() ``` 在这个示例中,`MySQLWrapper`封装了与MySQL数据库的连接和查询操作。它的构造函数接受数据库的主机名、用户名、密码和数据库名作为参数,并创建了一个数据库连接和游标对象。`execute_query`方法用于执行查询操作并返回结果,`execute_update`方法用于执行更新操作(例如插入、更新或删除数据),`close`方法用于关闭数据库连接。 要使用这个封装,你需要先安装`pymysql`库,可以使用以下命令进行安装: ``` pip install pymysql ``` 然后,你可以实例化`MySQLWrapper`,并调用其中的方法来执行相应的数据库操作。在使用完毕后,记得调用`close`方法关闭数据库连接。 这只是一个简单的示例,实际上,你可以根据需要扩展这个封装,添加更多的功能和方法来满足不同的需求。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

山河念远之追寻

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值