简体   繁体   English

C#数据表作为SQL参数的安全性

[英]Safety of C# DataTable as SQL Parameter

I read a lot about SQL injections lately and I know a SqlParameter will not prevent injections for sure, but is a table parameter as safe as a single parameter? 我最近阅读了很多有关SQL注入的信息,并且我知道SqlParameter不能肯定地阻止注入,但是表参数和单个参数一样安全吗?

Some untested uncompiled example code for clarification: 一些未经测试的未经编译的示例代码可用于澄清:

Is this... 这是...

SQL: SQL:

CREATE PROCEDURE dbo.InsertSingle 
    @Name nvarchar(max),
    @Phone nvarchar(max)
AS
BEGIN
    SET NOCOUNT ON; 

    INSERT INTO FooBar.dbo.SomeTable 
    VALUES(@Name, @Phone)
END
GO

C#: C#:

foreach(User u in Users) 
{
     Connection.Open();

     SqlCommand com = Connection.CreateCommand();
     com.CommandType = CommandType.StoredProcedure;
     com.CommandText = "dbo.InsertSingle";

     SqlParameter p = new SqlParameter("@Name", u.Name);
     com.Parameters.Add(p);

     p = new SqlParameter("@Phone", u.Phone);
     com.Parameters.Add(p);

     com.ExecuteScalar();
}

as safe as this? 像这样安全吗?

SQL: SQL:

CREATE PROCEDURE dbo.InsertBunch 
    @ValuesAsTable dbo.ValuesAsTableType READONLY
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO FooBar.dbo.SomeTable 
        SELECT * 
        FROM @ValuesAsTable
END
GO

C#: C#:

DataTable valuesAsTable = Users.GetSomeInsertData();
Connection.Open();

SqlCommand com = Connection.CreateCommand();
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "dbo.InsertBunch";

SqlParameter p = new SqlParameter("@valuesAsTable", valuesAdTable);
p.SqlDbType = SqlDbType.Structured;
p.TypeName = "dbo.ValuesAsTableType";
com.Parameters.Add(p);

com.ExecuteScalar();

I really tried to search it, but I cannot find good input. 我确实尝试搜索它,但是找不到很好的输入。 Can anyone link me in the right direction? 谁能以正确的方向联系我?

Thanks in advance 提前致谢

Typed parameters will prevent SQL injection if there is no possibility that they get interpreted as literal commands, and executed. 如果无法将类型的参数解释为文字命令并执行,则类型化的参数将阻止SQL注入。 Whether they are transported as scalar or table-valued parameters, does not make any difference in this regard. 无论将它们作为标量还是表值参数进行传输,在这方面都没有任何区别。

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

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