sqlalchemy建表与增删改查语句
时间: 2023-09-07 11:17:37 浏览: 42
可以在Python中使用SQLAlchemy库来创建表,增加、删除、修改和查询数据。
首先需要导入SQLAlchemy库:
``` python
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('mysql+pymysql://root:password@localhost/dbname?charset=utf8')
Base = declarative_base()
Session = sessionmaker(bind=engine)
```
接着,定义表格的ORM映射类,例如:
``` python
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name = Column(String(64), index=True)
email = Column(String(120), unique=True)
def __repr__(self):
return '<User %r>' % self.name
```
然后,在数据库中创建表:
```
Base.metadata.create_all(engine)
```
添加数据的代码:
``` python
session = Session()
user = User(name='test', email='test@example.com')
session.add(user)
session.commit()
```
查询数据的代码:
``` python
users = session.query(User).all()
for user in users:
print(user.name, user.email)
```
更新数据的代码:
``` python
user = session.query(User).filter_by(name='test').first()
user.email = 'new_email@example.com'
session.commit()
```
删除数据的代码:
``` python
user = session.query(User).filter_by(name='test').first()
session.delete(user)
session.commit()
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)