如何在Python中将用户变量插入SQL Update/Select语句
Python操作SQL:变量插入与记录打印
一、安全插入/更新SQL变量(避免SQL注入)
绝对不要用字符串拼接或格式化插入用户变量,这会引发SQL注入风险,还容易出现语法错误。正确做法是使用参数化查询,不同数据库驱动的占位符写法略有差异:
示例1:使用Python内置sqlite3
import sqlite3 def update_inv_quant(): new_quant = int(input("Enter the updated quantity in stock: ")) item_name = input("Enter the item name to update: ") # 指定要更新的商品 # 连接数据库 conn = sqlite3.connect('inventory.db') cursor = conn.cursor() # 用?作为占位符,变量通过元组传入 update_sql = "UPDATE Inv SET Quantity = ? WHERE ItemName = ?" cursor.execute(update_sql, (new_quant, item_name)) # 提交更改并关闭连接 conn.commit() conn.close()
示例2:使用MySQL驱动(mysql-connector-python)
import mysql.connector def update_inv_quant(): new_quant = int(input("Enter the updated quantity in stock: ")) item_name = input("Enter the item name to update: ") # 建立数据库连接 conn = mysql.connector.connect( host="localhost", user="你的用户名", password="你的密码", database="你的数据库名" ) cursor = conn.cursor() # MySQL用%s作为占位符 update_sql = "UPDATE Inv SET Quantity = %s WHERE ItemName = %s" cursor.execute(update_sql, (new_quant, item_name)) conn.commit() conn.close()
你之前尝试的("INSERT INTO Inv(ItemName) Value {user_iname)")写法有两个问题:
- 语法错误:
Value应为VALUES,右括号符号写错(应为}而非)) - 存在SQL注入风险,属于不安全写法
正确的参数化INSERT示例:
# sqlite3的INSERT示例 insert_sql = "INSERT INTO Inv(ItemName, Quantity) VALUES (?, ?)" cursor.execute(insert_sql, ("香蕉", 30))
二、查询并打印数据库记录
以sqlite3为例,查询并打印所有库存记录:
import sqlite3 def print_inv_records(): conn = sqlite3.connect('inventory.db') cursor = conn.cursor() # 查询所有记录 cursor.execute("SELECT * FROM Inv") all_records = cursor.fetchall() # 获取全部查询结果 # 打印记录 print("库存列表:") for idx, record in enumerate(all_records, 1): print(f"第{idx}条:商品名={record[0]}, 库存={record[1]}") # 按字段索引拆分打印 conn.close()
如果只需打印指定字段,可修改SQL语句:
# 只查询商品名和库存 cursor.execute("SELECT ItemName, Quantity FROM Inv")
内容的提问来源于stack exchange,提问作者iaivazovski
相关产品推荐
相关产品推荐

