我如何使创建帐户的代码免受 SQL-注入的影响?

How would I make my code which creates accounts safe from SQL-Injections?

这是我的代码:

import sqlite3
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS accounts(name text primary key, password text)')
connection.commit()
connection.close()

continue_loop = True
yes_no_value = input("Would you like to create a new account? (yes/no): ")
if yes_no_value == 'no':
    continue_loop = False

while continue_loop:

    user = input("Enter username: ")
    password = input("Enter password: ")
    connection = sqlite3.connect('data.db')
    cursor = connection.cursor()
    cursor.execute(f'INSERT INTO accounts VALUES("{user}", "{password}")')
    connection.commit()
    connection.close()
    print('success')
    yes_no_value = input("Would you like to create a new account? (yes/no): ")
    if yes_no_value == 'no':
        continue_loop == False

如果有人可以将我的代码发送给我但经过编辑以防止 SQL 注入并进行解释,这将有所帮助。

在您提供的代码中,存在注入风险的代码是这一行:

cursor.execute(f'INSERT INTO accounts VALUES("{user}", "{password}")')

所以,你要担心的是userpassword的值在那个时候的安全性。您允许用户从控制台输入它们,因此他们基本上可以输入任何内容。

您可以改为:

cursor.execute(f'INSERT INTO accounts VALUES(?, ?)', (user, password))

这具有相同的结果,但现在 cursor.execute()(或底层调用)将 userpassword 的值转换为 SQL 的值并具有有机会在这个过程中抓住恶作剧。