python与数据库连接
时间: 2024-12-16 22:06:55 浏览: 2
Python与数据库的连接是通过各种数据库驱动库来实现的。不同的数据库需要使用不同的库来连接和操作。以下是一些常见的数据库及其对应的Python库:
1. **MySQL**:
- 示例代码:
```python
import mysql.connector
conn = mysql.connector.connect(
host='localhost',
user='yourusername',
password='yourpassword',
database='yourdatabase'
)
cursor = conn.cursor()
cursor.execute("SELECT * FROM yourtable")
result = cursor.fetchall()
for row in result:
print(row)
cursor.close()
conn.close()
```
2. **PostgreSQL**:
- 库:`psycopg2`
- 示例代码:
```python
import psycopg2
conn = psycopg2.connect(
host='localhost',
database='yourdatabase',
user='yourusername',
password='yourpassword'
)
cursor = conn.cursor()
cursor.execute("SELECT * FROM yourtable")
result = cursor.fetchall()
for row in result:
print(row)
cursor.close()
conn.close()
```
3. **SQLite**:
- 库:`sqlite3` (内置库)
- 示例代码:
```python
import sqlite3
conn = sqlite3.connect('yourdatabase.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM yourtable")
result = cursor.fetchall()
for row in result:
print(row)
cursor.close()
conn.close()
```
4. **MongoDB**:
- 库:`pymongo`
- 示例代码:
```python
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client['yourdatabase']
collection = db['yourcollection']
results = collection.find()
for document in results:
print(document)
client.close()
```
这些库提供了丰富的功能来连接和操作数据库,包括执行SQL语句、处理结果集、管理事务等。
阅读全文