python db類用法說明
我就廢話不多說了,大家還是直接看代碼吧~
import pymysql
class DB:
__host = 'localhost' # 服務器地址
__username = 'root' # 用戶名
__password = '' # 密碼
__database = 'test' # 數(shù)據庫
__field = '*' # 查詢字段
__where = '' # 條件
__sql = False # 是否返回sql
__join = '' # 聯(lián)表
__order = '' # 排序
__limit = '' # 數(shù)量
# 構造函數(shù),在生成對象時調用
def __init__(self, table):
try:
# 打開數(shù)據庫連接 host, username, password, database
self.db = pymysql.connect(self.__host, self.__username, self.__password, self.__database)
except Exception as e:
print(e)
exit()
# 使用 cursor() 方法創(chuàng)建一個游標對象 cursor
self.cursor = self.db.cursor()
self.table = table
# 析構函數(shù),釋放對象時使用
def __del__(self):
try:
# 關閉數(shù)據庫連接
self.db.close()
except Exception as e:
print(e)
# 得到當前sql語句
def getSql(self):
self.__sql = True
return self
# 字段
def field(self, str):
self.__field = str
return self
# 聯(lián)表
def join(self, table, where):
self.__join = ' LEFT JOIN ' + table + ' ON ' + where + ' '
return self
# 條件
def where(self, param):
self.__where = ' WHERE '
if isinstance(param, list):
for i in param:
if isinstance(i[2], list):
tmp = '('
for j in i[2]:
tmp += str(j) + ','
tmp += ')'
self.__where += '`' + i[0] + '` ' + i[1] + ' ' + tmp + ' AND '
else:
self.__where += '`' + i[0] + '` ' + i[1] + ' ' + str(i[2]) + ' AND '
else:
self.__where = self.__where[0:-4]
else:
self.__where += param
return self
# 排序
def order(self, str):
self.__order = ' ORDER BY ' + str
return self
# 數(shù)量
def limit(self, str):
self.__limit = ' LIMIT ' + str
return self
# 增加
def insert(self, dict):
key = value = ''
for k, v in dict.items():
key += '`' + k + '`,'
value += '"' + v + '",'
key = key[0:-1]
value = value[0:-1]
sql = 'INSERT INTO ' + self.table + ' (' + key + ') VALUES (' + value + ')'
if self.__sql:
return sql
try:
# 執(zhí)行sql語句
ret = self.cursor.execute(sql)
# 提交到數(shù)據庫執(zhí)行
self.db.commit()
return ret
except Exception as e:
# 如果發(fā)生錯誤則回滾
self.db.rollback()
print(e)
return 0
# 刪除
def delete(self):
if self.__where:
sql = "DELETE FROM " + self.table + self.__where
if self.__sql:
return sql
try:
# 執(zhí)行sql語句
ret = self.cursor.execute(sql)
# 提交到數(shù)據庫執(zhí)行
self.db.commit()
return ret
except Exception as e:
# 如果發(fā)生錯誤則回滾
self.db.rollback()
print(e)
return 0
else:
raise BaseException('沒有條件') # 拋異常
# 修改
def update(self, dict):
str = ''
for k, v in dict.items():
str += '`' + k + '`="' + v + '",'
str = str[0:-1]
sql = 'UPDATE ' + self.table + ' SET ' + str
if self.__where:
sql += self.__where
if self.__sql:
return sql
try:
# 執(zhí)行sql語句
ret = self.cursor.execute(sql)
# 提交到數(shù)據庫執(zhí)行
self.db.commit()
return ret
except Exception as e:
# 如果發(fā)生錯誤則回滾
self.db.rollback()
print(e)
return 0
# 查詢
def select(self):
sql = "SELECT " + self.__field + " FROM " + self.table
if self.__join:
sql += self.__join
if self.__where:
sql += self.__where
if self.__order:
sql += self.__order
if self.__limit:
sql += self.__limit
if self.__sql:
return sql
# 使用 execute() 方法執(zhí)行 SQL 查詢
self.cursor.execute(sql)
# 使用 fetchall() 方法獲取所有數(shù)據.
data = self.cursor.fetchall()
return data
'''
DROP TABLE IF EXISTS `people`;
CREATE TABLE `people` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '名字',
`sex` varchar(7) DEFAULT '' COMMENT '性別',
`job` varchar(6) DEFAULT '' COMMENT '工作',
`age` varchar(6) DEFAULT '' COMMENT '年齡',
`height` varchar(6) DEFAULT '' COMMENT '身高',
`weight` varchar(6) DEFAULT '' COMMENT '體重',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
INSERT INTO `people` VALUES ('1', '趙一', '男', '學生', '8', '120', '35');
INSERT INTO `people` VALUES ('2', '錢二', '女', '學生', '9', '111', '31');
INSERT INTO `people` VALUES ('3', '孫三', '男', '學生', '10', '123', '34');
INSERT INTO `people` VALUES ('4', '李四', '女', '學生', '11', '100', '30');
'''
db = DB('people')
# 增加
dict = {'name': '周五', 'sex': '男', 'job': '學生', 'age': '8', 'height': '121', 'weight': '32'}
data = db.insert(dict)
print(data)
# 刪除
# data = db.where('id=6').delete()
# print(data)
# 修改
# dict = {'age': '9', 'height': '121', 'weight': '31'}
# data = db.where('id=7').update(dict)
# print(data)
# 查詢 優(yōu)化where條件 'id<11'
# data = db.field('id,name,age,job').where([['id', '>', 1]]).order('id desc').limit('3').select()
# print(data)
補充知識:python DB API cursor 常用接口
1. description
如果 cursor 執(zhí)行了查詢的 sql 代碼。那么讀取 cursor.description 屬性的時候,將返回一個列表,這個列表中裝的是元組,元組中裝的分別
是 (name,type_code,display_size,internal_size,precision,scale,null_ok) ,其中 name 代表的是查找出來的數(shù)據的字段名稱,其他參數(shù)暫時用處不大。
2. rowcount
代表的是在執(zhí)行了 sql 語句后受影響的行數(shù)。
3. close
關閉游標。關閉游標以后就再也不能使用了,否則會拋出異常。
4. execute(sql[,parameters])
執(zhí)行某個 sql 語句。如果在執(zhí)行 sql 語句的時候還需要傳遞參數(shù),那么可以傳給 parameters 參數(shù)。示例代碼如下:
cursor.execute("select * from article where id=%s",(1,))
5. fetchone
在執(zhí)行了查詢操作以后,獲取第一條數(shù)據。
6. fetchmany(size)
在執(zhí)行查詢操作以后,獲取多條數(shù)據。具體是多少條要看傳的 size 參數(shù)。如果不傳 size 參數(shù),那么默認是獲取第一條數(shù)據。
7. fetchall
獲取所有滿足 sql 語句的數(shù)據。
以上這篇python db類用法說明就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
- python drf各類組件的用法和作用
- python定義類的簡單用法
- Python面向對象程序設計之靜態(tài)方法、類方法、屬性方法原理與用法分析
- Python面向對象程序設計之類和對象、實例變量、類變量用法分析
- python編程進階之類和對象用法實例分析
- Python面向對象中類(class)的簡單理解與用法分析
- Python3變量與基本數(shù)據類型用法實例分析
- Python 面向對象之類class和對象基本用法示例
- python定義類self用法實例解析
- Python中類似于jquery的pyquery庫用法分析
- Python上下文管理器類和上下文管理器裝飾器contextmanager用法實例分析
- 詳細介紹python類及類的用法
相關文章
詳談Python 窗體(tkinter)表格數(shù)據(Treeview)
今天小編就為大家分享一篇詳談Python 窗體(tkinter)表格數(shù)據(Treeview),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10
Python多線程編程threading模塊使用最佳實踐及常見問題解析
這篇文章主要為大家介紹了Python多線程編程threading模塊使用最佳實踐及常見問題解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01
numpy存取數(shù)據(tofile/fromfile)的實現(xiàn)
本文主要介紹了numpy存取數(shù)據(tofile/fromfile)的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-02-02

