Python3 数据库操作小封装
生活随笔
收集整理的這篇文章主要介紹了
Python3 数据库操作小封装
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
import pymysql'''SQLController:對(duì)數(shù)據(jù)庫(kù)操作私有:__sql_connect(self):作用:建立數(shù)據(jù)庫(kù)連接 返回:數(shù)據(jù)庫(kù)連接對(duì)象__sql_insert_info(self, insert_sql):insert_sql: sql語(yǔ)句,默認(rèn)為空作用:數(shù)據(jù)插入__sql_delete_info(self, delete_sql):delete_sql: sql語(yǔ)句,默認(rèn)為空作用:刪除數(shù)據(jù)__sql_update_info(self, update_sql):update_sql: sql語(yǔ)句,默認(rèn)為空作用:更新數(shù)據(jù)__sql_select_info(self, select_sql):select_sql: sql語(yǔ)句,默認(rèn)為空作用:查詢(xún)數(shù)據(jù) 公共:sql_close(self):關(guān)閉數(shù)據(jù)庫(kù)連接 sql_handle(self, handle, sql):handle:操作方式,默認(rèn)為空,不區(qū)分大小寫(xiě)值:SQL_INSERT:插入數(shù)據(jù)操作SQL_DELETE:刪除數(shù)據(jù)操作SQL_UPDATE:更新數(shù)據(jù)操作SQL_SELECT:查詢(xún)數(shù)據(jù)操作sql:sql語(yǔ)句,默認(rèn)為空作用:數(shù)據(jù)的增刪改查操作handle_table(self, handle, name, sql):handle:操作方式,默認(rèn)為空,不區(qū)分大小寫(xiě)值:SHOW_TABLES:顯示所有的數(shù)據(jù)表TABLE_IS_EXIST:判斷某數(shù)據(jù)表是否存在CREATE_TABLE:創(chuàng)建數(shù)據(jù)表SHOW_COLUMNS:顯示某數(shù)據(jù)表的列名name:數(shù)據(jù)表名稱(chēng),默認(rèn)為空sql:sql語(yǔ)句,默認(rèn)為空作用:查詢(xún)表是否存在以及創(chuàng)建表
'''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#連接數(shù)據(jù)庫(kù)def __sql_connect(self):db = pymysql.connect(self.__hostname, self.__username, self.__password, self.__dbname)return db#關(guān)閉數(shù)據(jù)庫(kù)連接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)#表和數(shù)據(jù)庫(kù)的操作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)#增加數(shù)據(jù)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()#查詢(xún)數(shù)據(jù)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!')#更新數(shù)據(jù)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()#刪除數(shù)據(jù)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()#數(shù)據(jù)庫(kù)連接測(cè)試def sql_connect_test(self):db = self.__sql_connect()cursor = db.cursor()cursor.execute('select version()')data = cursor.fetchone()print('database version : %s' % data) #模塊測(cè)試(測(cè)試不完整)
# 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')
轉(zhuǎn)載于:https://www.cnblogs.com/softwarecrash/p/8934409.html
總結(jié)
以上是生活随笔為你收集整理的Python3 数据库操作小封装的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: CentOS bug修复指令集(阿里云漏
- 下一篇: python 代理的使用