Python3 database operation small package

import pymysql

'''
    SQLController: Operation on the database
        private:
            __sql_connect(self):
                Role: establish a database connection   
                Returns: database connection object
            __sql_insert_info(self, insert_sql):
                insert_sql: sql statement, default is empty
                Role: data insertion
            __sql_delete_info(self, delete_sql):
                delete_sql: sql statement, default is empty
                Function: delete data
            __sql_update_info(self, update_sql):
                update_sql: sql statement, default is empty
                Function: update data
            __sql_select_info(self, select_sql):
                select_sql: sql statement, default is empty
                Function: query data    
        public:
            sql_close(self):
                close database connection         
            sql_handle(self, handle, sql):
                handle: operation mode, the default is empty, case insensitive
                    value:
                        SQL_INSERT: insert data operation
                        SQL_DELETE: delete data operation
                        SQL_UPDATE: update data operation
                        SQL_SELECT: query data operation
                sql: sql statement, default is empty
                Function: data addition, deletion, modification and query operations
            handle_table(self, handle, name, sql):
                handle: operation mode, the default is empty, case insensitive
                    value:
                        SHOW_TABLES: show all data tables
                        TABLE_IS_EXIST: Determine whether a data table exists
                        CREATE_TABLE: Create a data table
                        SHOW_COLUMNS: Display the column names of a data table
                name: data table name, default is empty
                sql: sql statement, default is empty
                Role: query whether the table exists and create a table
'''

class SQLController():

    __hostname = ''
    __username = ''
    __password = ''
    __dbname = ''

    def __init__(self, hostname = '', username = '', password = '', dbname = ''):
        if hostname == '' and username == '' and password == '' and dbname == '':
            print("No hostname or username or password or dbname!")
            pass
        else:
            self.__hostname = hostname
            self.__username = username
            self.__password = password
            self.__dbname = dbname

    #Connect to the database
    def __sql_connect(self):
        db = pymysql.connect(self.__hostname, self.__username, self.__password, self.__dbname)
        return db

    #Close the database connection
    def sql_close(self):
        self.__sql_connect().close()

    #sql use
    def sql_handle(self, handle = '', sql = ''):
        handle = handle.upper()
        if sql == '':
            print('SQL is empty')
            return 0
        if handle == '':
            print('Handle is empty')
            return 0
        if handle == 'SQL_INSERT':
            self.__sql_insert_info(sql)
        elif handle == 'SQL_DELETE':
            self.__sql_delete_info(sql)
        elif handle == 'SQL_SELECT':
            self.__sql_select_info(sql)
        elif handle == 'SQL_UPDATE':
            self.__sql_update_info(sql)
        else:
            print('%s Error, use SQL_INSERT or SQL_DELETE or SQL_UPDATE or SQL_SELECT' % handle)

    #Operation of tables and databases
    def handle_table(self, handle = '', name = '', sql = ''):
        if handle == 'CREATE_TABLE' and sql == '':
            print('No name of table and database!')
            return 0
        if handle == 'SHOW_COLUMNS' and name == '':
            print('No table has been selected!')
            return 0
        try:
            handle = handle.upper()
            db = self.__sql_connect()
            cursor = db.cursor()
            if handle == 'SHOW_TABLES' or handle == 'TABLE_IS_EXIST':
                cursor.execute('show tables')
                tables = cursor.fetchall()
                if len(tables) == 0:
                    print('No Tables, You Need Create!')
                for table in tables:
                    if handle == 'SHOW_TABLES':
                        print(table[0])
                    elif handle == 'TABLE_IS_EXIST':
                        if name == table[0]:
                            print('%s exist!' % name)
                        else:
                            print('No %s!' % name)
                cursor.close()
            elif handle == 'CREATE_TABLE':
                cursor.execute('%s' % sql)
                db.commit()
                cursor.close()
                print('%s create success!' % name)
            elif handle == 'SHOW_COLUMNS':
                cursor.execute('show columns from %s' % name)
                column = cursor.fetchall()
                for i in column:
                    print(i[0])
                cursor.close()
                print('Success')
        except:
            print('%s Error' % handle)


    #add data
    def __sql_insert_info(self, insert_sql):
        try:
            db = self.__sql_connect()
            cursor = db.cursor()
            cursor.execute(insert_sql)
            db.commit()
            cursor.close()
            print('Insert success')
        except:
            print('Insert Info Failed!')
            db.rollback()

    #Query data
    def __sql_select_info(self, select_sql):
        try:
            db = self.__sql_connect()
            cursor = db.cursor()
            cursor.execute(select_sql)
            result = cursor.fetchall()
            for row in result:
                print(row[0])
            cursor.close()
            print('Select success')
        except:
            print('Display Info Failed!')

    #update data
    def __sql_update_info(self, update_sql):
        try:
            db = self.__sql_connect()
            cursor = db.cursor()
            cursor.execute(update_sql)
            db.commit()
            cursor.close()
            print('Update success')
        except:
            print('Update Info Failed!')
            db.rollback()

    #delete data
    def __sql_delete_info(self, delete_sql):
        try:
            db = self.__sql_connect()
            cursor = db.cursor()
            cursor.execute(delete_sql)
            db.commit()
            cursor.close()
            print('Delete success')
        except:
            print('Delete Info Failed!')
            db.rollback()

    #Database connection test
    def sql_connect_test(self):
        db = self.__sql_connect()
        cursor = db.cursor()
        cursor.execute('select version()')
        data = cursor.fetchone()
        print('database version : %s' % data)
#模块测试(测试不完整)
# if __name__ == '__main__':
# sqlc = SQLController('localhost', 'root', '123456', 'MovieInfo')
# sqlc.sql_connect_test()
# sqlc.table_handle('SHOW_TABLE')
# m = 10
# sql_lang = 'insert into b(age) values (%d)' % m
# sqlc.sql_handle('SQL_INSERT', sql_lang)
# sql_lang_2 = 'select * from b'
# sql_lang_3 = 'delete from b where age = %d' % m
# sqlc.sql_handle('SQL_SELECT', sql_lang_2)
# sqlc.sql_handle('SQL_delete', sql_lang_3)
# sqlc.sql_handle('SQL_SELECT', sql_lang_2)
# sqlc.handle_table('SHOW_TABLES')
# sqlc.handle_table('TABLE_IS_EXIST', 'a')
# sqlc.handle_table('CREATE_TABLE', '', 'create table c (sex varchar(10))')
# sqlc.handle_table('SHOW_TABLES')
# sqlc.handle_table('SHOW_COlumns', 'a')

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324805234&siteId=291194637