用python開發(fā)一款操作MySQL的小工具
https://github.com/lishukan/directsql
安裝pip3 install directsql導(dǎo)入
directsql 目前只提供三個(gè)外部類
__all__=['SqlGenerator','MysqlConnection','MysqlPool']
導(dǎo)入方式
from directsql.sqlgenerator import SqlGenerator #該類用于生成sql語句#下面是一個(gè)池化連接對象MysqlPool 和一個(gè)簡單連接對象 MysqlConnectorfrom directsql.connector import MysqlConnection,MysqlConnector 使用1 創(chuàng)建連接
# 1. 傳入有名參數(shù) conn = MysqlConnection(host=’127.0.0.1’, port=3306, password=’123456’, database=’test_base’) print(conn.database) conn=MysqlPool(host=’127.0.0.1’, port=3306, password=’123456’, database=’test_base’) # 也可使用 直接 參數(shù)字典 conn_args = {’host’: ’127.0.0.1’,’port’: 3306,’password’: ’123456’,’database’:’test_base’, } conn = MysqlConnection(**conn_args)#單個(gè)連接 print(conn.database) conn = MysqlPool(**conn_args) #池化連接對象 print(conn.database) #2 直接使用 字符串 #以下字符串是常用的終端 連接命令 string_arg='mysql -uroot -h127.0.0.1 -P3306 -p123456 -Dtest_base' conn = MysqlConnection(string_arg=string_arg) print(conn.database) conn = MysqlPool(string_arg=string_arg) print(conn.database) 2 執(zhí)行sql語句
事實(shí)上directsql 封裝了 很多 語句。可以滿足很大一部分日常使用場景。但是如果有復(fù)雜的語句,仍然需要調(diào)用原生的sql 執(zhí)行。而且directsql 中很多封裝好的方法是先拼接sql 再 調(diào)用該語句,所以這里還是先簡單介紹下,directsql 如何執(zhí)行原生sql。
無論是 MysqlConnection 類 還是 MysqlPool 類 都通過 execute_sql 方法 來執(zhí)行sql。
例如 :
id name age 1 羅輯 28 2 莊顏 25 3 葉文潔 54 4 程心 25 5 云天明 27
conn = MysqlConnection(string_arg='mysql -uroot -h127.0.0.1 -P3306 -p123456 -Dtest')result,count=conn.execute_sql('select * from test_table ')print(result)print(count)>>> ((1, ’羅輯’, ’28’), (2, ’莊顏’, ’25’), (3, ’葉文潔’, ’54’), (4, ’程心’, ’25’), (5, ’云天明’, ’27’))>>> 5 #這里默認(rèn)是普通游標(biāo),你也可以指定使用字典游標(biāo):result, count = conn.execute_sql('select * from test_table ', cursor_type=’dict’)>>>[{’ID’: 1, ’name’: ’羅輯’, ’age’: ’28’}, {’ID’: 2, ’name’: ’莊顏’, ’age’: ’25’}, {’ID’: 3, ’name’: ’葉文潔’, ’age’: ’54’}, {’ID’: 4, ’name’: ’程心’, ’age’: ’25’}, {’ID’: 5, ’name’: ’云天明’, ’age’: ’27’}]>>>5
execute_sql 方法 返回的是一個(gè)元組,(結(jié)果集,條數(shù))
下文出現(xiàn)的所有方法無特殊說明都是返回元組,且支持dict游標(biāo)
附帶參數(shù)執(zhí)行語句
這里的參數(shù)使用起來和 pymysql 提供的 execute 以及executemany 沒有任何 差別,以下簡單提供幾個(gè)示例:
#傳元組result,count=conn.execute_sql('select * from test_table where age=%s ',param=(25,))#傳字典result, count = conn.execute_sql('select * from test_table where age=%(age)s ', param={’age’: 25})#元組列表result, count = conn.execute_sql('insert into test_table(`age`,`name`)values(%s,%s) ', param=[(’宋運(yùn)輝’, 37), (’程開顏’, 33)])#字典列表result, count = conn.execute_sql('insert into test_table(`age`,`name`)values(%(age)s,%(name)s) ',param=[ {'name':'宋運(yùn)輝',’age’:37}, {'name':'程開顏',’age’:33} ])3 select 方法
select 方法 可以接受多參數(shù),參數(shù)列表如下。
def select(self, columns=’id’, table=None, where=None, group_by: str = None, order_by: str = None, limit: int = None, offset=None,cursor_type=None):
》》》 conn.select(’*’, ’test_table’)
select id from test_table where age=25》》》 conn.select(’*’, ’test_table’, where={’age’: 25})
select name,age from test_table where age=25 and id=2多字段直接傳入字符串
》》》 conn.select('age,name', ’test_table’, where={’age’: 25,’id’:2})
傳入列表/元組
》》》 conn.select([’age’,’name’], ’test_table’, where={’age’: 25,’id’:2})
select * from test_table group by id order by age desc limit 1 offset 1》》》conn.select(’*’, ’test_table’, order_by=’age desc’,group_by=’id’,limit=1,offset=1)
select 功能看起來甚至不如直接寫原生sql 快,但是如果查詢條件是在不斷變化的,尤其是where條件,那么使用select 方法 會(huì)比自行拼接更方便。
例如,需要不斷地讀取一個(gè)字典變量,然后根據(jù)這個(gè)變量中的條件去查詢數(shù)據(jù),而這個(gè)字典的鍵個(gè)數(shù)會(huì)變化,但是鍵都恰好是表的字段。這個(gè)時(shí)候使用select 方法會(huì)十分簡便,只需要令where參數(shù)等于那個(gè)字典即可。
平心而論,這個(gè)方法確實(shí)用處不大。
4 insert_into 方法def insert_into(self, table, data: dict or list, columns=None, ignroe=False, on_duplicate_key_update: str = None, return_id=False):
該方法可以接受傳入字典或者 字典列表,并且可選 返回 游標(biāo)影響的條數(shù) 或者是 新插入的數(shù)據(jù)的id。
columns 為空時(shí),將取第一條數(shù)據(jù)的所有鍵,此時(shí)請確保所有數(shù)據(jù)鍵相同。
#傳入 字典data_1 = {'age': 44, ’name’: '雷東寶'}count = conn.insert_into(’test_table’, data_1)#默認(rèn)返回受影響條數(shù)print(count) #>>> 1 return_id = conn.insert_into(’test_table’, data_1,return_id=True)# 可選返回idprint(return_id)>>>22533 #傳入字典列表data_2={'age': 22, ’name’: '宋運(yùn)萍'}all_data=[data_1,data_2]count = conn.insert_into(’test_table’, all_data)#限定 插入的字段。(字典有多字段,但是只需要往表里插入指定的字段時(shí))data_3= {'age': 44, ’name’: '雷東寶','title':'村支書'} #title不需要,只要age和namecount = conn.insert_into(’test_table’, data_1,columns=['age','name'] )#ignore 參數(shù)data_1 = {'age': 44, ’name’: '雷東寶','id':22539}count = conn.insert_into(’test_table’,ignore=True )print(count)>>> 0 # 由于表中id 22539 已經(jīng)存在,該條記錄不會(huì)插入,影響 0條數(shù)據(jù)#on_duplicate_key_update 參數(shù)data_1 = {'age': 44, ’name’: '雷東寶','id':22539} #id=22539 已經(jīng)存在count = conn.insert_into(’test_table’, data_1,on_duplicate_key_update=’ name='雷copy' ’)print(count)#返回影響條數(shù)>>>2 #嘗試插入一條,但是發(fā)生重復(fù),于是刪除新數(shù)據(jù),并更新舊數(shù)據(jù)。實(shí)際上影響了兩條。
在insert_into 方法中提供了 on_duplicate_key_update 參數(shù),但是實(shí)際上使用起來比較雞肋,需要自己傳入 on_duplicate_key_update 后的語句進(jìn)行拼接。
如果你僅僅只是需要在發(fā)生重復(fù)時(shí)將舊數(shù)據(jù)的特定字段更新為新數(shù)據(jù)對應(yīng)字段的值時(shí)。merge_into 方法更適合。
5 merge_into 方法在 其他關(guān)系型數(shù)據(jù)庫中,提供有merge into 的語法,但是mysql 中沒有提供。 不過這里我們通過insert 和 on_duplicate_key_update 語法 封裝出了一個(gè) 類似merge_into 的方法。 該方法返回的是影響的條數(shù)
def* merge_into(self, table, data, columns=None, need_merge_columns: list = None):
columns 為空時(shí),將取第一條數(shù)據(jù)的所有鍵,此時(shí)請確保所有數(shù)據(jù)鍵相同。
need_merge_columns 為在發(fā)生重復(fù)時(shí)需要替換(覆蓋)的字段。
data_1 = {'age': 44, ’name’: '雷東寶','id':22539}data_2={'age': 22, ’name’: '宋運(yùn)萍','id':22540}all_data = [data_1, data_2,]count=conn.merge_into(’test_table’,all_data,need_merge_columns=[’name’,])print(count)>>>4#兩條數(shù)據(jù)正好都是重復(fù)的,插入兩條又刪除后修改兩條 ,返回46 replace_into 方法
該方法簡單,不做過多說明。該方法 返回的是影響的條數(shù)
def replace_into(self,table, data: dict or list, columns=None)
data_1 = {'age': 44, ’name’: '雷東寶','id':22539}data_2={'age': 22, ’name’: '宋運(yùn)萍','id':22540}all_data = [data_1, data_2,]count=conn.replace_into(’test_table’,all_data)7 update 方法
def update(self,table, data: dict, where, columns: None or list = None, limit=None):
該方法data 參數(shù)只接受傳入字典。該方法 返回的是影響的條數(shù)
data_1 = {'age': 44, ’name’: '雷copy'}count=conn.update(’test_table’,data_1,where={’id’:22539}) #更新 id=22539的數(shù)據(jù)為 新的data_1print(count)>>>1
除此之外,還提供了一個(gè)衍生的方法
def update_by_primary(self, table, data: dict, pri_value, columns=None, primary: str = ’id’):
用于通過主鍵去更新數(shù)據(jù)。pri_value 即為主鍵的值。primary 為主鍵,默認(rèn)為id
data_1 = {'age': 44, ’name’: '雷cpy'}count=conn.update_by_primary(’test_table’,data_1,pri_value=22539)8 delete 方法
def delete_by_primary(self, table, pri_value, primary=’id’):'''通過主鍵刪除數(shù)據(jù)'''def delete(self,table, where: str or dict, limit: int = 0):'''通過where條件刪除數(shù)據(jù)'''count=conn.delete(’test_table’,where={’name’:’雷東寶’}) #刪除name=雷東寶的數(shù)據(jù)count=conn.delete_by_primary(’test_table’,pri_value=22539) #刪除主鍵等于22539 的數(shù)據(jù)9 使用 事務(wù)
def do_transaction(self, sql_params: list, cursor_type=None):
sql_params 為 元組列表。 【(sql_1,param_1),(sql_2,param_2】
如果sql 不需要參數(shù)也要傳入 None ,如 【(sql_1,None),】
sql_params = [('update test_table set name=%(name)s where id=%(id)s ', {’name’: ’洛基’, ’id’: 22539}),('update test_table set name=%(name)s where id=%(id)s ', {’name’: ’mask’, ’id’: 22540}), ]count=conn.do_transaction(sql_params)>>>((), 1) #返回最后一條執(zhí)行語句的 結(jié)果和影響條數(shù)10 讀取流式游標(biāo)結(jié)果
def read_ss_result(self, sql, param=None, cursor_type=’ss’):
cursor_type 可選 ss 和 ssdict
注意,該方法返回的是 生成器對象,拿到結(jié)果需要不斷進(jìn)行遍歷。
result=conn.read_ss_result('select * from test_table')for data in result:print(data)
以上就是python開發(fā)一款操作MySQL的小工具的詳細(xì)內(nèi)容,更多關(guān)于python 操作MySQL的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. HTML5 Canvas繪制圖形從入門到精通2. HTTP協(xié)議常用的請求頭和響應(yīng)頭響應(yīng)詳解說明(學(xué)習(xí))3. 不要在HTML中濫用div4. XML入門的常見問題(三)5. HTML DOM setInterval和clearInterval方法案例詳解6. HTML5實(shí)戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)7. CSS清除浮動(dòng)方法匯總8. 本站用的rss輸出9. Vue如何使用ElementUI對表單元素進(jìn)行自定義校驗(yàn)及踩坑10. XML在語音合成中的應(yīng)用
