使用python连接数据库
时间: 2024-09-22 07:05:29 浏览: 63
在Python中,连接数据库通常会通过使用一些库来实现,其中最常用的是SQLAlchemy和sqlite3(如果数据库是SQLite)。以下是基本步骤:
1. **安装库**:
- SQLAlchemy:使用pip安装 `pip install sqlalchemy`
- sqlite3:内置在Python中,无需额外安装。
2. **连接到SQLite数据库** (使用sqlite3):
```python
import sqlite3
conn = sqlite3.connect('example.db') # 连接到名为example.db的数据库
```
3. **连接到其他数据库** (使用SQLAlchemy):
```python
from sqlalchemy import create_engine
engine = create_engine('postgresql://username:password@localhost/dbname') # 链接URL替换为实际数据库地址
conn = engine.connect()
```
4. **创建连接池** (推荐做法,避免频繁建立连接):
```python
from sqlalchemy.pool import QueuePool
pool = QueuePool(engine, max_overflow=-1)
conn = pool.connect()
```
5. **执行查询**:
```python
cursor = conn.cursor()
cursor.execute("SELECT * FROM table_name")
result = cursor.fetchall()
```
6. **关闭连接**:
```python
cursor.close()
conn.close()
```
阅读全文
相关推荐














