Python3 数据库操作小封装
生活随笔
收集整理的這篇文章主要介紹了
Python3 数据库操作小封装
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
import pymysql'''SQLController:對數據庫操作私有:__sql_connect(self):作用:建立數據庫連接 返回:數據庫連接對象__sql_insert_info(self, insert_sql):insert_sql: sql語句,默認為空作用:數據插入__sql_delete_info(self, delete_sql):delete_sql: sql語句,默認為空作用:刪除數據__sql_update_info(self, update_sql):update_sql: sql語句,默認為空作用:更新數據__sql_select_info(self, select_sql):select_sql: sql語句,默認為空作用:查詢數據 公共:sql_close(self):關閉數據庫連接 sql_handle(self, handle, sql):handle:操作方式,默認為空,不區分大小寫值:SQL_INSERT:插入數據操作SQL_DELETE:刪除數據操作SQL_UPDATE:更新數據操作SQL_SELECT:查詢數據操作sql:sql語句,默認為空作用:數據的增刪改查操作handle_table(self, handle, name, sql):handle:操作方式,默認為空,不區分大小寫值:SHOW_TABLES:顯示所有的數據表TABLE_IS_EXIST:判斷某數據表是否存在CREATE_TABLE:創建數據表SHOW_COLUMNS:顯示某數據表的列名name:數據表名稱,默認為空sql:sql語句,默認為空作用:查詢表是否存在以及創建表
'''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!")passelse:self.__hostname = hostnameself.__username = usernameself.__password = passwordself.__dbname = dbname#連接數據庫def __sql_connect(self):db = pymysql.connect(self.__hostname, self.__username, self.__password, self.__dbname)return db#關閉數據庫連接def sql_close(self):self.__sql_connect().close()#sql使用def sql_handle(self, handle = '', sql = ''):handle = handle.upper()if sql == '':print('SQL is empty')return 0if handle == '':print('Handle is empty')return 0if 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)#表和數據庫的操作def handle_table(self, handle = '', name = '', sql = ''):if handle == 'CREATE_TABLE' and sql == '':print('No name of table and database!')return 0if handle == 'SHOW_COLUMNS' and name == '':print('No table has been selected!')return 0try: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)#增加數據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()#查詢數據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!')#更新數據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()#刪除數據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()#數據庫連接測試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')
# 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')
轉載于:https://www.cnblogs.com/softwarecrash/p/8934409.html
總結
以上是生活随笔為你收集整理的Python3 数据库操作小封装的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CentOS bug修复指令集(阿里云漏
- 下一篇: python 代理的使用