python中cursor sql语句占位符
时间: 2025-03-27 22:01:26 浏览: 45
### Python 中使用 SQL 占位符的最佳实践
在 Python 中执行 SQL 查询时,推荐使用参数化查询来防止 SQL 注入攻击并提高代码可读性和维护性。对于不同的数据库驱动程序,占位符语法可能有所不同。
#### 使用 `sqlite3` 库作为示例:
当使用 SQLite 数据库时,可以采用命名风格或问号风格的占位符[^1]。
```python
import sqlite3
connection = sqlite3.connect(':memory:')
cursor = connection.cursor()
# 创建表结构
cursor.execute('CREATE TABLE users(id INTEGER PRIMARY KEY, username TEXT NOT NULL);')
# 插入单条记录 - 使用问号风格 (?)
cursor.execute('INSERT INTO users(username) VALUES(?);', ('alice',))
# 批量插入多条记录 - 使用问号风格 (?)
users_to_insert = [
('bob',),
('carol',)
]
cursor.executemany('INSERT INTO users(username) VALUES(?);', users_to_insert)
# 查询数据 - 使用命名风格 (:name)
cursor.execute('SELECT * FROM users WHERE id=:uid;', {'uid': 1})
result = cursor.fetchone()
print(result)
```
#### 使用 `psycopg2` 连接 PostgreSQL 数据库:
PostgreSQL 的 psycopg2 驱动支持百分号 (`%s`) 和扩展样式 (`%(key)s`) 参数绑定方式。
```python
import psycopg2
conn = psycopg2.connect(dbname="testdb", user="postgres", password="secret")
cur = conn.cursor()
# 插入操作 - 使用 %s 样式的占位符
cur.execute(
"INSERT INTO employees(first_name, last_name) VALUES (%s, %s)",
("John", "Doe"),
)
# 更新操作 - 同样适用 %s 或者 %(key)s 方式
update_query = """
UPDATE employees SET salary=%(salary)s
WHERE first_name=%(fname)s AND last_name=%(lname)s;
"""
cur.execute(update_query, {
'salary': 70000,
'fname': 'Jane',
'lname': 'Smith'
})
conn.commit() # 记得提交事务
```
#### 安全提示与最佳实践建议:
- 总是优先考虑预编译语句和参数化查询;
- 不要拼接字符串构建最终 SQL 命令;
- 对于批量处理场景,利用 `executemany()` 方法提升效率;
- 尽量减少硬编码常数值,在适当情况下定义配置文件或环境变量存储敏感信息。
阅读全文
相关推荐


















