python pymysq Demo

已经封装好了

# 导入模块
import sys

import pymysql


class mysqlDemo():
    # 初始化
    def __init__(self, host, user, password, database, charset="utf8"):
        # 连接database
        connection = pymysql.connect(
            host=host,
            user=user,
            password=password,
            database=database,
            charset=charset)
        self.connection = connection
        self.cursor = connection.cursor()
        print("\033[37;41m 连接数据库成功\033[0m")

    # 关闭连接  
    def closeDB(self):
        self.cursor.close()
        self.connection.close()

    # 创建表
    def createTable(self):
        # 成员变量转换
        cursor = self.cursor
        connection = self.connection
        tableName = input('输入表名:')  # 获取表名
        columns = ''  # 用来存储用户输入的所有字段
        while True:
            print('==========================================================================='
                  '===========================================================================')
            print("\033[37;41m 输入0则退出添加字段\033[0m")
            columnName = input('输入一个字段和类型(例如 id INT auto_increment PRIMARY KEY):')
            if columnName.__eq__('0'):  # 退出字段添加循环
                break
            # 完善逗号结尾
            columnName = columnName.replace(',', '').strip()  # 去除逗号 然后去除两端空格
            columns = columns.strip() + columnName + ','  # 把字段添加到总字段

        columns = columns.strip()[:-1]  # 最后一个字段不需要逗号

        # SQL语句
        sql = """
        CREATE TABLE %s (
        %s
        )ENGINE=innodb DEFAULT CHARSET=utf8; 
        """ % (tableName, columns)  # 变量填充sql语句中的%s
        try:
            self.cursor.execute(sql)  # 执行SQL语句
            print("\033[37;41m 创建表成功 \033[0m")
            self.closeDB()  # 关闭资源
        # 异常处理
        except:
            print("\033[37;41m 创建表失败 \033[0m")
            print(sys.exc_info())  # 输出异常

    # 删除表
    def dropTable(self):
        # 成员变量转换
        cursor = self.cursor
        connection = self.connection
        try:
            tableName = input('输入表名:')
            sql = 'drop table %s ' % tableName + ';'  # SQL语句
            cursor.execute(sql)  # 执行SQL语句
            print("\033[37;41m 删除表成功 \033[0m")
            self.closeDB()  # 关闭资源
        except:
            print("\033[37;41m 删除表失败 \033[0m")
            print(sys.exc_info())  # 输出异常信息

    '''
    tableName 表名
    columns 表的列名(str、list格式)
    values 插入的数值(str、list格式)
    '''

    # 向表中插入数据
    def insertToTable(self, tableName, columns, values):
        # 成员变量转换
        cursor = self.cursor
        connection = self.connection
        # 确保输入的columns、values参数类型为str或者list
        if not ((isinstance(columns, str) and isinstance(values, str)) or (
                isinstance(columns, list) and isinstance(values, list))):
            print("\033[37;41m 参数columns和values类型必须是list或者str且两者保持类型一致 \033[0m")
            exit(1)

        # 如果输入的参数是str类型,统一转换成list类型
        if isinstance(columns, str):
            # columns转换
            temp = []
            temp.append(columns)
            columns = temp
            # values转换
            temp = []
            temp.append(values)
            values = temp
        # columns和values要一一对应
        if len(columns) != len(values):
            print("\033[37;41m columns和values个数不一致 \033[0m")
            exit(1)

        allColumns = ''  # columns SQL语句
        allValues = ''  # values SQL语句
        for i in columns:
            allColumns = allColumns + i + ','  # 拼接SQL格式的columns
            allValues = allValues + '%s,'  # 拼接SQL格式的values
        allColumns = allColumns[:-1]  # 最后一个逗号无意义  去除
        allValues = allValues[:-1]  # 最后一个逗号无意义  去除
        # SQL语句
        sql = 'INSERT INTO ' + tableName + '(' + allColumns + ')VALUES(' + allValues + ');'
        try:

            cursor.execute(sql, values)  # 执行sql语句
            connection.commit()  # 提交
            print("\033[37;41m 插入数据成功 \033[0m")
            self.closeDB()  # 关闭资源
        except:  # 异常处理
            # Rollback in case there is any error
            print("\033[37;41m 插入数据失败 \033[0m")
            print(sys.exc_info())  # 输出异常信息
            connection.rollback()  # 回滚

    '''
    tableName 表名
    columns 列名(str、list格式)
    values 对应列的的数值(str、list格式)
    '''

    # 删除表中的数据
    def deleteDataFromTable(self, tableName, columns, values):
        # 成员变量转换
        cursor = self.cursor
        connection = self.connection
        # 确保输入的columns、values参数类型为str或者list
        if not ((isinstance(columns, str) and isinstance(values, str)) or (
                isinstance(columns, list) and isinstance(values, list))):
            print("\033[37;41m 参数columns和values类型必须是list或者str且两者保持类型一致 \033[0m")
            exit(1)
        # 如果输入的参数是str类型,统一转换成list类型
        if isinstance(columns, str):
            # columns转换
            temp = []
            temp.append(columns)
            columns = temp
            # values转换
            temp = []
            temp.append(values)
            values = temp
        # columns和values要一一对应
        if len(columns) != len(values):
            print("\033[37;41m columns和values个数不一致 \033[0m")
            exit(1)
        allColumns = ''  # SQLcolumns语句
        # 拼接SQL语句
        for i in columns:
            allColumns = allColumns + i + ' = %s and '
        allColumns = allColumns[:-4]  # 去除最后一个and
        # SQL语句
        sql = 'delete from  ' + tableName + ' where ' + allColumns + ';'
        try:
            cursor.execute(sql, values)  # 执行sql语句
            connection.commit()  # 提交
            print("\033[37;41m 删除数据成功 \033[0m")
            self.closeDB()  # 关闭资源
        except:  # 异常处理
            # Rollback in case there is any error
            print("\033[37;41m 删除数据失败 \033[0m")
            print(sys.exc_info())  # 输出异常数据
            connection.rollback()  # 回滚

    '''
    tableName 表名
    columns 查找的列名(str、list格式)
    values 对应列的的数值(str、list格式)
    setColumn 更新列的列名(str、list格式)
    setValue 更新列的值(str、list格式)
    '''

    # 更改表中的数据
    def updateDataFromTable(self, tableName, columns, values, setColumns, setValues):
        # 成员变量转换
        cursor = self.cursor
        connection = self.connection
        # 确保输入的columns、values、setColumns、setValues参数类型为str或者list
        if not ((isinstance(columns, str) and isinstance(values, str)) or (
                isinstance(columns, list) and isinstance(values, list))):
            print("\033[37;41m 参数columns和values类型必须是list或者str且两者保持类型一致 \033[0m")
            exit(1)
        if not ((isinstance(setColumns, str) and isinstance(setValues, str)) or (
                isinstance(setColumns, list) and isinstance(setValues, list))):
            print("\033[37;41m 参数setColumns和setValues类型必须是list或者str且两者保持类型一致 \033[0m")
            exit(1)
        # 如果输入的参数是str类型,统一转换成list类型
        if isinstance(columns, str):
            # 转换columns
            temp = []
            temp.append(columns)
            columns = temp
            # 转换values
            temp = []
            temp.append(values)
            values = temp
        if isinstance(setColumns, str):
            # 转换setColumns
            temp = []
            temp.append(setColumns)
            setColumns = temp
            # 转换setValues
            temp = []
            temp.append(setValues)
            setValues = temp

        # columns和values要一一对应
        if len(columns) != len(values):
            print("\033[37;41m columns和values个数不一致 \033[0m")
            exit(1)
        # setColumns和setValues要一一对应
        if len(setColumns) != len(setValues):
            print("\033[37;41m setColumns和setValues个数不一致 \033[0m")
            exit(1)
        allColumns = ''  # columns SQL语句
        # 拼接SQL语句
        for i in columns:
            allColumns = allColumns + i + ' = %s and '
        allColumns = allColumns[:-4]  # 去除最后一个and

        allSetColumns = ''  # SetColumns SQL语句
        # 拼接SetColumns语句
        for i in setColumns:
            allSetColumns = allSetColumns + i + ' = %s , '
        allSetColumns = allSetColumns[:-2]  # 去除最后一个,
        # SQl语句
        sql = 'update ' + tableName + ' set ' + allSetColumns + ' where ' + allColumns + ';'
        # SQL语句中的参数叠加
        allValues = setValues + values
        try:
            cursor.execute(sql, allValues)  # 执行sql语句
            connection.commit()  # 提交
            print("\033[37;41m 更新数据成功 \033[0m")
            self.closeDB()  # 关闭资源
        except:  # 异常处理
            # Rollback in case there is any error
            print("\033[37;41m 更新数据失败 \033[0m")
            print(sys.exc_info())  # 输出异常数据
            connection.rollback()  # 回滚

    '''
    tableName: 表名
    lineNumber:显示数据条数(默认10条)
    showColumns:查找的字段(默认'*')
    whereColumns:筛选的字段(默认'')
    whereValues=:筛选的值(默认'')
    orderByColumns:排序的字段(默认'')
    orderByDescOrAsc:排序是升序还是降序(默认为'' 此参数<=orderByColumns。不写此参数,一律所有字段asc)
    '''

    # 从表中查找数据(只是查询  不涉及数据过滤处理等复杂操作)
    def selectDataFromTable(self, tableName, lineNumber=10, showColumns='*', whereColumns='', whereValues='',
                            orderByColumns='',
                            orderByDescOrAsc=''):
        # 成员变量转换
        cursor = self.cursor
        connection = self.connection
        # 确保输入的showColumns、whereColumns、whereValues、orderByColumns等参数类型为str或者list
        if not isinstance(lineNumber, int):
            print("\033[37;41m 参数lineNumber类型必须是int \033[0m")
            exit(1)
        if not (isinstance(showColumns, str) or isinstance(showColumns, list)):
            print("\033[37;41m 参数showColumns类型必须是list或者str \033[0m")
            exit(1)
        if not ((isinstance(whereColumns, str) and isinstance(whereValues, str)) or (
                isinstance(whereColumns, list) and isinstance(whereValues, list))):
            print("\033[37;41m 参数whereColumns和whereValues类型必须是list或者str且两者保持类型一致 \033[0m")
            exit(1)
        if not (isinstance(orderByColumns, str) or isinstance(orderByColumns, list)):
            print("\033[37;41m 参数showColumns类型必须是list \033[0m")
            exit(1)
        if not (isinstance(orderByDescOrAsc, str) or isinstance(orderByDescOrAsc, list)):
            print("\033[37;41m 参数showColumns类型必须是list \033[0m")
            exit(1)

        # 如果输入的参数是str类型,统一转换成list类型
        if isinstance(showColumns, str):
            temp = []
            temp.append(showColumns)
            showColumns = temp

        if isinstance(whereColumns, str):
            temp = []
            temp.append(whereColumns)
            whereColumns = temp
            temp = []
            temp.append(whereValues)
            whereValues = temp

        if isinstance(orderByColumns, str):
            temp = []
            temp.append(orderByColumns)
            orderByColumns = temp
            temp = []
            temp.append(orderByDescOrAsc)
            orderByDescOrAsc = temp
        # whereColumns和whereValues要一一对应
        if len(whereColumns) != len(whereValues):
            print("\033[37;41m whereColumns和whereValues个数不一致 \033[0m")
            exit(1)
        # orderByColumns和orderByDescOrAsc要一一对应
        if len(orderByColumns) < len(orderByDescOrAsc):
            print("\033[37;41m orderByDescOrAsc个数大于orderByColumns的个数 \033[0m")
            exit(1)

        # 填充orderByDescOrAsc字段(如果未写 默认升序)
        orderByTemp = []
        orderByTemp = orderByColumns.copy()
        bl = len(orderByDescOrAsc)  # orderByDescOrAsc长度
        al = len(orderByColumns)  # orderByColumns长度
        for i in range(al):
            if i < bl:
                orderByTemp[i] = orderByDescOrAsc[i]
            else:
                orderByTemp[i] = 'asc'
        orderByDescOrAsc = orderByTemp
        # 拼接SQL的select
        sql = 'select  '
        for i in showColumns:
            if i.__eq__('*'):  # 默认值
                sql = sql + i + ','
                break
            else:  # 输入值
                sql = sql + i + ','
        sql = sql[:-1]  # 去除','

        sql = sql + ' from ' + tableName  # 拼接SQL的from

        # 拼接SQL的where
        sql = sql + ' where '
        for i in whereColumns:
            if i.__eq__(''):  # 默认值
                sql = sql[:-6]  # 去除'where '
                sql = sql + '    '
                break
            else:  # 输入的值
                sql = sql + i + ' = %s ' + 'and '
        sql = sql[:-4]  # 去除'and '
        # 拼接SQL的order by
        sql = sql + ' order by '
        for i in orderByColumns:
            if i.__eq__(''):  # 默认值
                sql = sql[:-9]
                sql = sql + ' '
                break
            else:  # 输入的值
                sql = sql + i + ' = %s %s ' + ','
        sql = sql[:-1] + ';'  # 去除','
        allValues = []  # SQL语句中的参数叠加
        cursor = connection.cursor(cursor=pymysql.cursors.DictCursor)  # 返回字典数据类型
        # 没有where语句和order by 语句
        if whereValues[0].__eq__('') and orderByColumns[0].__eq__(''):
            cursor.execute(sql)
        else:
            # where语句
            if not whereValues[0].__eq__(''):
                allValues = allValues + whereValues.copy()
            # order by语句
            if not orderByDescOrAsc[0].__eq__(''):
                allValues = allValues + orderByColumns + orderByDescOrAsc.copy()
            cursor.execute(sql, allValues)
        # 按照lineNumber数量循环遍历数据
        while lineNumber > 0:
            info = cursor.fetchone()
            if info is None:
                break
            print(info)
            lineNumber = lineNumber - 1
        self.closeDB()  # 关闭资源

代码如下 ``` #!/usr/bin/env python # -*- coding:utf-8 -*- # Author:lcj import pymysql #连接数据库 conn = pymysql.connect(host='172.26.11.46',port= 3306,user = 'root',passwd='123456',db='mytest_db') #创建游标 cur = conn.cursor() #插入一条数据 # reCount = cur.excute('insert into lcj(name,age) vaules(%s,%s)',('ff',18)) #向test库中的lcj表插入 # ret = cur.executemany("insert into lcj(name,tel)values(%s,%s)", [("kk",13212344321),("kw",13245678906)]) #同时向数据库lcj表中插入多条数据 #ret = cur.executemany("insert into lcj values(%s,%s,%s,%s,%s)", [(41,"xiaoluo41",'man',24,13212344332),(42,"xiaoluo42",'gril',21,13245678948),(43,"xiaoluo43",'gril',22,13245678949),(44,"xiaoluo44",'main',24,13543245648)]) #提交 conn.commit() #关闭指针对象 cur.close() #关闭连接对象 conn.close() #打印结果 print(ret) ``` 错误如下: File "aadd.py", line 6, in <module> conn = pymysql.connect(host='172.26.11.46',port= 3306,user = 'root',passwd='123456',db='mytest_db') File "/usr/local/lib/python3.4/dist-packages/PyMySQL3-0.5-py3.4.egg/pymysql/__init__.py", line 93, in Connect File "/usr/local/lib/python3.4/dist-packages/PyMySQL3-0.5-py3.4.egg/pymysql/connections.py", line 510, in __init__ File "/usr/local/lib/python3.4/dist-packages/PyMySQL3-0.5-py3.4.egg/pymysql/connections.py", line 676, in _connect File "/usr/local/lib/python3.4/dist-packages/PyMySQL3-0.5-py3.4.egg/pymysql/connections.py", line 830, in _get_server_information File "/usr/local/lib/python3.4/dist-packages/PyMySQL3-0.5-py3.4.egg/pymysql/charset.py", line 173, in charset_by_id File "/usr/local/lib/python3.4/dist-packages/PyMySQL3-0.5-py3.4.egg/pymysql/charset.py", line 21, in by_id KeyError: 46 求大神指导
©️2020 CSDN 皮肤主题: 创作都市 设计师:CSDN官方博客 返回首页