简体   繁体   English

SQL代码注入是否安全? (以及为什么)

[英]Is this code safe from SQL injections? (and why)

Is this code safe from SQL injections? SQL代码注入是否安全? Why? 为什么?

public void AddPlayer(string username)
    {
        var query = "INSERT INTO dbo.Player(Username, RegisterDate) VALUES(@Username, @RegisterDate)";
        using (var connection = new SqlConnection(connectionString))
        using (var command = new SqlCommand(query, connection))
        {
            command.Parameters.AddWithValue("@Username", username);
            command.Parameters.AddWithValue("@RegisterDate", DateTime.Now);
            command.Connection.Open();
            command.ExecuteNonQuery();
        }
    }

    public DateTime GetRegisterDate(string username)
    {
        var query = "SELECT RegisterDate FROM dbo.Player WHERE Username = @Username";
        using (var connection = new SqlConnection(connectionString))
        using (var command = new SqlCommand(query, connection))
        {
            command.Parameters.AddWithValue("@Username", username);
            command.Connection.Open();
            return (DateTime)command.ExecuteScalar();
        }
    }

EDIT: Could injection-safe equivalent code be written using a stored procedure? 编辑:可以使用存储过程编写注入安全的等效代码吗? If so, what the stored procedure would be like? 如果是这样,存储过程会是什么样的?

Yes, It looks safe. 是的,它看起来很安全。

Because it uses parameters. 因为它使用参数。

You run a risk of SQL-injection when you create queries like 当您创建类似的查询时,您会冒着SQL注入的风险
baseQueryText + " WHERE Username =" + TextBox.Text;

Reguarding the Edit: When you use a Stored Procedure you always use parameters so they are safe too. 调用编辑:当您使用存储过程时,您始终使用参数,因此它们也是安全的。 No special effort required, but you still could/should filter incoming data. 无需特殊工作,但您仍然可以/应该过滤传入的数据。

Yes. 是。 You are using parameterized queries, which are in general considered safe from SQL injection. 您正在使用参数化查询,这些查询通常被认为是安全的SQL注入。

You may still want to consider filtering your inputs anyway. 您仍可能需要考虑过滤输入。

是的,所有非静态数据都是通过绑定参数输入的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM