亚洲免费在线视频-亚洲啊v-久久免费精品视频-国产精品va-看片地址-成人在线视频网

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

用python開(kāi)發(fā)一款操作MySQL的小工具

瀏覽:3日期:2022-06-19 18:59:27
目錄項(xiàng)目地址安裝導(dǎo)入使用1 創(chuàng)建連接2 執(zhí)行sql語(yǔ)句​3 select 方法4 insert_into 方法5 merge_into 方法6 replace_into 方法7 update 方法8 delete 方法9 使用 事務(wù)10 讀取流式游標(biāo)結(jié)果項(xiàng)目地址

https://github.com/lishukan/directsql

安裝

pip3 install directsql導(dǎo)入

directsql 目前只提供三個(gè)外部類

__all__=['SqlGenerator','MysqlConnection','MysqlPool']

導(dǎo)入方式

from directsql.sqlgenerator import SqlGenerator #該類用于生成sql語(yǔ)句#下面是一個(gè)池化連接對(duì)象MysqlPool 和一個(gè)簡(jiǎn)單連接對(duì)象 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) #池化連接對(duì)象 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語(yǔ)句​

事實(shí)上directsql 封裝了 很多 語(yǔ)句。可以滿足很大一部分日常使用場(chǎng)景。但是如果有復(fù)雜的語(yǔ)句,仍然需要調(diào)用原生的sql 執(zhí)行。而且directsql 中很多封裝好的方法是先拼接sql 再 調(diào)用該語(yǔ)句,所以這里還是先簡(jiǎn)單介紹下,directsql 如何執(zhí)行原生sql。

​ 無(wú)論是 MysqlConnection 類 還是 MysqlPool 類 都通過(guò) execute_sql 方法 來(lái)執(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)的所有方法無(wú)特殊說(shuō)明都是返回元組,且支持dict游標(biāo)

附帶參數(shù)執(zhí)行語(yǔ)句

這里的參數(shù)使用起來(lái)和 pymysql 提供的 execute 以及executemany 沒(méi)有任何 差別,以下簡(jiǎn)單提供幾個(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), (’程開(kāi)顏’, 33)])#字典列表result, count = conn.execute_sql('insert into test_table(`age`,`name`)values(%(age)s,%(name)s) ',param=[ {'name':'宋運(yùn)輝',’age’:37}, {'name':'程開(kāi)顏',’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 功能看起來(lái)甚至不如直接寫原生sql 快,但是如果查詢條件是在不斷變化的,尤其是where條件,那么使用select 方法 會(huì)比自行拼接更方便。

​ 例如,需要不斷地讀取一個(gè)字典變量,然后根據(jù)這個(gè)變量中的條件去查詢數(shù)據(jù),而這個(gè)字典的鍵個(gè)數(shù)會(huì)變化,但是鍵都恰好是表的字段。這個(gè)時(shí)候使用select 方法會(huì)十分簡(jiǎn)便,只需要令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í)請(qǐng)確保所有數(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':'村支書(shū)'} #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í)際上使用起來(lái)比較雞肋,需要自己傳入 on_duplicate_key_update 后的語(yǔ)句進(jìn)行拼接。

如果你僅僅只是需要在發(fā)生重復(fù)時(shí)將舊數(shù)據(jù)的特定字段更新為新數(shù)據(jù)對(duì)應(yīng)字段的值時(shí)。merge_into 方法更適合。

5 merge_into 方法

在 其他關(guān)系型數(shù)據(jù)庫(kù)中,提供有merge into 的語(yǔ)法,但是mysql 中沒(méi)有提供。 不過(guò)這里我們通過(guò)insert 和 on_duplicate_key_update 語(yǔ)法 封裝出了一個(gè) 類似merge_into 的方法。 該方法返回的是影響的條數(shù)

def* merge_into(self, table, data, columns=None, need_merge_columns: list = None):

columns 為空時(shí),將取第一條數(shù)據(jù)的所有鍵,此時(shí)請(qǐng)確保所有數(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 方法

該方法簡(jiǎn)單,不做過(guò)多說(shuō)明。該方法 返回的是影響的條數(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’):

用于通過(guò)主鍵去更新數(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’):'''通過(guò)主鍵刪除數(shù)據(jù)'''def delete(self,table, where: str or dict, limit: int = 0):'''通過(guò)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í)行語(yǔ)句的 結(jié)果和影響條數(shù)10 讀取流式游標(biāo)結(jié)果

def read_ss_result(self, sql, param=None, cursor_type=’ss’):

cursor_type 可選 ss 和 ssdict

注意,該方法返回的是 生成器對(duì)象,拿到結(jié)果需要不斷進(jìn)行遍歷。

result=conn.read_ss_result('select * from test_table')for data in result:print(data)

以上就是python開(kāi)發(fā)一款操作MySQL的小工具的詳細(xì)內(nèi)容,更多關(guān)于python 操作MySQL的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 欧美一区2区 | 在线看片亚洲 | 久久综合久久美利坚合众国 | 欧美日韩成人在线视频 | 999热成人精品国产免 | 精品国产一区二区三区www | 美女张开腿让男人桶下面 | avtt加勒比手机版天堂网 | 国产亚洲欧美日韩综合综合二区 | 中文字幕在线视频精品 | 国产精品深爱在线 | 亚洲精品一区二区三区四区手机版 | 国产精品极品美女自在线看免费一区二区 | 国产成人深夜福利短视频99 | 亚洲欧美在线综合一区二区三区 | 免费高清特级毛片 | 三上悠亚免费一区二区在线 | 亚洲视频99| 久久国产精品高清一区二区三区 | 亚洲日韩视频免费观看 | 欧美人交性视频在线香蕉 | 综合精品 | 欧美日韩精品一区二区另类 | 亚洲国产片 | 久久久久久网站 | 最新99国产成人精品视频免费 | 中文精品久久久久国产网址 | 成人爽a毛片在线视频网站 成人爽爽大片在线观看 | 精品 日韩 国产 欧美在线观看 | 亚洲 欧美 国产 日韩 制服 bt | fc2在线播放 | 久久久亚洲欧洲日产国码二区 | 老妇激情毛片 | 国模午夜写真福利视频在线 | www.一区| 免费国产a国产片高清不卡 免费国产不卡午夜福在线 免费国产不卡午夜福在线观看 | 亚洲日本一区二区三区在线 | 亚洲欧洲日韩综合色天使不卡 | 久草视频福利在线观看 | 91精品在线免费 | 黄人成a动漫片免费网站 |