数据库的save python
时间: 2023-08-16 12:11:51 浏览: 59
在 Python 中,可以使用多种方式将数据保存到数据库。以下是一些常见的方法:
1. 使用 Python 内置的 sqlite3 模块保存数据到 SQLite 数据库:
```python
import sqlite3
# 创建数据库连接
conn = sqlite3.connect('database.db')
# 创建游标对象
cursor = conn.cursor()
# 创建表格(如果不存在)
cursor.execute('''CREATE TABLE IF NOT EXISTS my_table (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER)''')
# 插入数据
data = ('John', 25)
cursor.execute('INSERT INTO my_table (name, age) VALUES (?, ?)', data)
# 提交更改
conn.commit()
# 关闭连接
conn.close()
```
2. 使用第三方库,如 SQLAlchemy,可以与多种数据库进行交互。以下是一个使用 SQLAlchemy 将数据保存到 MySQL 数据库的示例:
```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://username:password@localhost/database')
Session = sessionmaker(bind=engine)
session = Session()
# 创建模型类
Base = declarative_base()
class MyTable(Base):
__tablename__ = 'my_table'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
# 创建表格(如果不存在)
Base.metadata.create_all(engine)
# 插入数据
data = MyTable(name='John', age=25)
session.add(data)
session.commit()
# 关闭会话
session.close()
```
这些只是两个示例,具体的数据库保存方法取决于你使用的数据库类型和库。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)