增加数据:
INSERT INTO students (id, name, age) VALUES (1, '张三', 20);
删除数据:
DELETE FROM students WHERE id = 1;
更新数据:
UPDATE students SET age = 21 WHERE id = 1;
查询数据:
SELECT * FROM students;
强化部分,使用参数化查询以避免SQL注入:
import mysql.connector
# 假设有以下参数
id_to_delete = 1
new_age = 21
# 连接到数据库
conn = mysql.connector.connect(user='username', password='password', host='hostname', database='databasename')
cursor = conn.cursor()
# 删除操作
delete_query = "DELETE FROM students WHERE id = %s"
cursor.execute(delete_query, (id_to_delete,))
# 更新操作
update_query = "UPDATE students SET age = %s WHERE id = %s"
cursor.execute(update_query, (new_age, id_to_delete))
# 查询操作
select_query = "SELECT * FROM students"
cursor.execute(select_query)
results = cursor.fetchall()
for row in results:
print(row)
# 关闭游标和连接
cursor.close()
conn.close()
以上代码展示了如何使用参数化查询来安全地执行增删改查操作,避免了SQL注入的风险。