使用python 创建sql server 连接池类,进行查询
时间: 2024-05-07 08:15:52 浏览: 11
以下是一个简单的使用Python创建SQL Server连接池类的示例:
```python
import pyodbc
import queue
import threading
class SQLServerPool:
def __init__(self, server, database, username, password, max_pool_size=5):
self.server = server
self.database = database
self.username = username
self.password = password
self.max_pool_size = max_pool_size
self.pool = queue.Queue(maxsize=max_pool_size)
self.lock = threading.Lock()
def get_connection(self):
connection = None
try:
# Check if there is a connection in the pool
connection = self.pool.get_nowait()
except queue.Empty:
# If the pool is empty, create a new connection
connection = pyodbc.connect(
'DRIVER={SQL Server};SERVER=' + self.server + ';DATABASE=' + self.database + ';UID=' + self.username + ';PWD=' + self.password)
return connection
def return_connection(self, connection):
# Return the connection to the pool
with self.lock:
self.pool.put(connection)
def execute_query(self, query):
connection = self.get_connection()
cursor = connection.cursor()
cursor.execute(query)
result = cursor.fetchall()
self.return_connection(connection)
return result
```
在上述代码中,我们首先导入了pyodbc模块,然后定义了一个`SQLServerPool`类。此类构造函数接受以下参数:
- `server`: SQL Server的名称或IP地址
- `database`: 要连接的数据库名称
- `username`: 连接数据库的用户名
- `password`: 连接数据库的密码
- `max_pool_size`: 连接池中允许的最大连接数,默认为5
类中有三个主要的方法:
- `get_connection`: 返回一个可用的数据库连接。如果连接池中已经存在可用连接,则直接返回;否则创建一个新的连接并返回。
- `return_connection`: 将数据库连接返回到连接池中。
- `execute_query`: 执行给定的SQL查询并返回结果。
现在我们可以使用以下代码来创建一个`SQLServerPool`对象并执行SQL查询:
```python
# Create a SQL Server connection pool
pool = SQLServerPool('localhost', 'test', 'sa', 'password')
# Execute a query
result = pool.execute_query('SELECT * FROM MyTable')
# Print the results
for row in result:
print(row)
```
在上面的代码中,我们首先创建了一个`SQLServerPool`对象,并指定了连接到哪个SQL Server,哪个数据库以及使用哪个用户名和密码。接着我们执行了一个查询,并将结果打印到控制台上。
需要注意的是,由于我们使用了连接池,因此在执行查询后必须将连接返回到池中,否则连接将永远不会被释放,最终导致连接池中的所有连接都被耗尽。在上述代码中,我们使用了`return_connection`方法来返回连接。