pymysql 和 sqlalchemy
时间: 2023-12-20 20:31:59 浏览: 160
以下是关于pymysql和sqlalchemy的介绍:
1. pymysql模块:
```python
import pymysql
# 建立连接
connection = pymysql.connect(
host='localhost',
user='root',
password='******',
db='test_db',
charset='utf8',
cursorclass=pymysql.cursors.DictCursor
)
# 获取游标
cursor = connection.cursor()
# 执行SQL语句
cursor.execute("SELECT * FROM books")
# 获取结果
result = cursor.fetchall()
# 关闭连接
connection.close()
```
2. SQLAlchemy模块:
```python
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# 创建连接引擎
engine = create_engine('mysql+pymysql://root:******@localhost/test_db', echo=True)
# 创建基类
Base = declarative_base()
# 定义映射类
class Book(Base):
__tablename__ = 'books'
id = Column(Integer, primary_key=True)
title = Column(String(50))
author = Column(String(50))
# 创建表
Base.metadata.create_all(engine)
# 创建会话
Session = sessionmaker(bind=engine)
session = Session()
# 查询数据
books = session.query(Book).all()
# 关闭会话
session.close()
```
阅读全文