python 跑sql
时间: 2024-07-25 18:01:20 浏览: 48
在Python中运行SQL(Structured Query Language)通常通过数据库连接库来完成,例如`sqlite3`, `psycopg2`(PostgreSQL),`pyodbc`(ODBC支持)或更流行的ORM(Object-Relational Mapping)工具如`SQLAlchemy`, `pymysql`等。
1. 使用`sqlite3`模块(针对SQLite数据库):
```python
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM table_name")
rows = cursor.fetchall()
```
2. 对于像MySQL这样的关系型数据库,可以使用`pymysql`库:
```python
import pymysql
db = pymysql.connect(host='localhost', user='username', password='password', db='database_name')
cursor = db.cursor()
cursor.execute("SELECT * FROM table_name")
```
3. 使用ORM库如`SQLAlchemy`:
```python
from sqlalchemy import create_engine, select
engine = create_engine('mysql+mysqldb://user:pass@host/dbname')
with engine.connect() as connection:
result = connection.execute(select([Table.name]).where(Table.id == 1))
rows = result.all()
```
无论哪种方式,都要记得关闭连接以释放资源。在执行SQL之前,确保已经安装了相应的数据库驱动和库。
阅读全文