PYTHON 生成插入SQL语句
时间: 2023-02-14 11:05:40 浏览: 75
可以使用 Python 的第三方库如 sqlalchemy 或者 PyMySQL 生成插入 SQL 语句。
示例:使用 sqlalchemy 生成插入语句
```
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
# 创建连接
engine = create_engine("mysql+pymysql://root:password@localhost/testdb")
Base = declarative_base()
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
# 创建表
Base.metadata.create_all(bind=engine)
# 生成插入语句
ins = User.insert().values(name="John", age=30)
str(ins)
# 输出:'INSERT INTO users (name, age) VALUES (:name, :age)'
```
示例:使用 PyMySQL 生成插入语句
```
import pymysql
# 创建连接
conn = pymysql.connect(host="localhost", user="root", password="password", database="testdb")
cursor = conn.cursor()
# 生成插入语句
sql = "INSERT INTO users (name, age) VALUES ('John', 30)"
cursor.execute(sql)
```
请注意,在实际应用中,需要捕获异常并处理,以防止 SQL 注入攻击。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)