pytho实现数据库查询操作函数
时间: 2023-02-08 08:48:43 浏览: 71
在 Python 中,可以使用 SQLAlchemy 库来进行数据库查询操作。
首先,需要连接到数据库,可以使用 create_engine() 函数。
```python
from sqlalchemy import create_engine
engine = create_engine('数据库连接字符串')
```
然后,可以使用 connection() 函数来获取数据库连接,并使用 execute() 函数执行 SQL 查询语句。
```python
with engine.connect() as connection:
result = connection.execute("SELECT * FROM table_name WHERE condition")
```
最后,可以使用 fetchall() 或者 fetchone() 函数来获取查询结果。
```python
data = result.fetchall()
```
可以将上面的代码封装成函数来实现数据库查询操作。
```python
def query_data(query_str):
engine = create_engine('数据库连接字符串')
with engine.connect() as connection:
result = connection.execute(query_str)
data = result.fetchall()
return data
```
使用时直接调用函数即可,例如
```python
data = query_data("SELECT * FROM table_name WHERE condition")
```