1. 程式人生 > >pymysql封裝操作資料庫

pymysql封裝操作資料庫

pymysql封裝操作資料庫

安裝pymysql

#-i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com 指定使用阿里雲的源,可以不加
pip3 install pymysql http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com

簡單寫操作

import pymysql.cursors

# Connect to the database
connection = pymysql.connect(host='localhost',
                             user='user',
                             password='passwd',
                             db='db',
                             charset='utf8mb4',
                             cursorclass=
pymysql.cursors.DictCursor) try: with connection.cursor() as cursor: # Create a new record sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)" cursor.execute(sql, ('[email protected]', 'very-secret')) # connection is not autocommit by default. So you must commit to save your changes.
connection.commit() except Exception as e: print(e) # error rollback connection.rollback() finally: connection.close()

簡單讀操作

import pymysql.cursors

# Connect to the database
connection = pymysql.connect(host='localhost',
                             user='user',
                             password='passwd',
                             db='db',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:
        # Read a single record
        sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
        cursor.execute(sql, ('[email protected]',))
        result = cursor.fetchone()
        print(result)
except Exception as e:
    print(e)
finally:
    connection.close()

封裝工具類多操作

PyMysql.py

#! /usr/bin/env python3
# -*- coding:utf-8 -*-

import pymysql

class PyMysql:

    host = 'localhost'
    user = 'user'
    password = 'pwssword'
    db = 'test'
    charset = 'utf8mb4'
    cursorclass = pymysql.cursors.DictCursor

    @classmethod
    def query(cls,sql,args=None,fetchone=False):
        # 建立連線
        connection = pymysql.connect(host=cls.host, user=cls.user,
                                     password=cls.password, db=cls.db, charset =cls.charset, cursorclass = cls.cursorclass)
        try:
            result = None
            # 開啟遊標
            with connection.cursor() as cursor:
                # 返回響應結果數
                effect_row = cursor.execute(cls.sql_args_2_sql(sql, args))
                if fetchone:
                    result = cursor.fetchone()
                else:
                    result = cursor.fetchall()
        except Exception as e:
            print(e)
        finally:
            # 關閉連線
            connection.close()

        return result

    @classmethod
    def execute(cls,sql,args=None,response=False):
        connection = pymysql.connect(host=cls.host, user=cls.user,
                                     password=cls.password, db=cls.db, charset =cls.charset, cursorclass = cls.cursorclass)

        try:
            result = None
            with connection.cursor() as cursor:
                effect_row = cursor.execute(cls.sql_args_2_sql(sql, args))
                if response:
                    result = cursor.fetchall()

            # connection is not autocommit by default. So you must commit to save your changes.
            connection.commit()
        except Exception as e:
            print(e)
            # error rollback
            connection.rollback()
        finally:
            connection.close()

        if response:
            return result

    @staticmethod
    def sql_args_2_sql(sql,args):
        '''
        fix  issue  %d format: a number is required, not str
        :param sql: sql語句
        :param args: 格式化引數
        :return: 組合之後的sql語句
        '''
        if args is None:
            return sql
        if sql.find('%') > -1:
            return sql % args
        elif sql.find('{') > -1:
            if type(args) is dict:
                return sql.format(**args)
            else:
                return sql.format(*args)
        return sql


if __name__ == '__main__':
    #print(PyMysql.query(sql="select * from test where name = '%s' and age = %d ", args=('admin1', 18,), fetchone=True))
    #print(PyMysql.query(sql="select * from test where name = '{0}' and age = {1} ", args=('admin1', 18,),fetchone=True))
    #print(PyMysql.execute(sql="insert into test(name,gender,age) values('{name}','{gender}',{age})",args={'name':'admin6','gender':'女','age':18}))
    dict_result = PyMysql.query(sql="select * from test where name = '{0}' ", args=('admin1',),fetchone=True)
    print(dict_result)
    print(dict_result['name'],dict_result['age'],dict_result['gender'])

    PyMysql.execute(sql='UPDATE test set age = age +1 where id = %d ',args=(dict_result['id']))

    print(PyMysql.query(sql="select * from test where id = {0} ", args=(dict_result['id'],)))

    PyMysql.cursorclass = PyMysql.cursors.Cursor
    print(PyMysql.execute(sql="show tables",response=True))

%d format: a number is required, not str 錯誤解決

    @staticmethod
    def sql_args_2_sql(sql,args):
        '''
        fix  issue  %d format: a number is required, not str
        :param sql: sql語句
        :param args: 格式化引數
        :return: 組合之後的sql語句
        '''
        if args is None:
            return sql
        if sql.find('%') > -1:
            return sql % args
        elif sql.find('{') > -1:
            if type(args) is dict:
                return sql.format(**args)
            else:
                return sql.format(*args)
        return sql