資料庫連線池與SQL工具類

2022-09-18 15:45:13 字數 3446 閱讀 3603

# -*- coding: utf-8 -*-

'''@time : 2021/11/19 16:45

@author : ziqingbaojian

@file : mysql.py

'''# 依賴第三發包:pymysql,dbutils

import pymysql

from dbutils.pooled_db import pooleddb

mysql_db_pool=pooleddb(

creator=pymysql,

maxconnections=50,

mincached=2,

maxcached=3,

blocking=true,

setsession=,

ping=0,

host='127.0.0.1',

port=3306,

user='root',

password='1234567',

database='testlearn',

charset='utf8'

)

原始碼解釋

使用連線池

使用多執行緒進行測試

# 使用連線池

def task():

# 連線池獲取連線

conn=mysql_db_pool.connection()

cursor=conn.cursor()

cursor.execute("select * from student where sname='邏輯'")

result=cursor.fetchall()

print(result)

conn.close()#將連線還給連線池

# task()

'''使用多執行緒進行測試'''

def run():

for i in range(10):

t=threading.thread(target=task)

t.start()

if __name__ == '__main__':

# 開啟10個執行緒進行測試

2.1 單利模式的方式實現

實現單利模式的方式

使用

# -*- coding: utf-8 -*-

'''@time : 2021/11/20 8:24

@author : ziqingbaojian

@file : testpy.py

'''from db import db

'''使用單利模式進行操作'''

res=db.fetch_one("select * from student where sname='%s'"%("邏輯"))

print(res)

''''''

單利模式使用效果

補充:python其他實現單利模式的方法

2.2上下文管理

當主邏輯**沒有報異常時,這三個引數將都為none。

理解並使用 contextlib#

在上面的例子中,我們只是為了構建乙個上下文管理器,卻寫了乙個類。如果只是要實現乙個簡單的功能,寫乙個類未免有點過於繁雜。這時候,我們就想,如果只寫乙個函式就可以實現上下文管理器就好了。

這個點python早就想到了。它給我們提供了乙個裝飾器,你只要按照它的**協議來實現函式內容,就可以將這個函式物件變成乙個上下文管理器。

我們按照 contextlib 的協議來自己實現乙個開啟檔案(with open)的上下文管理器。

import contextlib

@contextlib.contextmanager

def open_func(file_name):

# __enter__方法

print('open file:', file_name, 'in __enter__')

file_handler = open(file_name, 'r')

# 【重點】:yield

yield file_handler

# __exit__方法

print('close file:', file_name, 'in __exit__')

file_handler.close()

return

with open_func('/users/ming/mytest.txt') as file_in:

for line in file_in:

print(line)

在被裝飾函式裡,必須是乙個生成器(帶有yield),而yield之前的**,就相當於__enter__裡的內容。yield 之後的**,就相當於__exit__裡的內容。

上面這段**只能實現上下文管理器的第乙個目的(管理資源),並不能實現第二個目的(處理異常)。

如果要處理異常,可以改成下面這個樣子。

import contextlib

@contextlib.contextmanager

def open_func(file_name):

# __enter__方法

print('open file:', file_name, 'in __enter__')

file_handler = open(file_name, 'r')

try:

yield file_handler

except exception as exc:

# deal with exception

print('the exception was thrown')

finally:

print('close file:', file_name, 'in __exit__')

file_handler.close()

return

with open_func('/users/ming/mytest.txt') as file_in:

for line in file_in:

1/0print(line)

複製知識點的參考文獻較多,主要是為了解釋編寫的資料庫使用的工具類中的知識點;

資料庫連線池 Redis連線池

基本原理 在內部物件池中,維護一定數量的資料庫連線,並對外暴露資料庫連線的獲取和返回方法。如外部使用者可通過getconnection方法獲取資料庫連線,使用完畢後再通過releaseconnection方法將連線返回,注意此時的連線並沒有關閉,而是由連線池管理器 並為下一次使用做好準備。2.作用 ...

Druid 資料庫連線池的工具類使用

1 定義乙個類 jdbcutils 2 提供靜態 塊載入配置檔案,初始化連線池物件 3 提供方法 獲取連線方法 通過資料庫連線池獲取連線 釋放資源 獲取連線池的方法public class jdbcutils catch ioexception e catch exception e 獲取連線 pu...

資料庫連線池

實現資料連線池,讓系統有更高有執行效率 using system using system.data using system.data.sqlclient using system.collections using system.threading public class dataaccess...