How do I protect this function from SQL injection?

前端 未结 11 1185
独厮守ぢ
独厮守ぢ 2020-12-16 18:47
public static bool TruncateTable(string dbAlias, string tableName)
{
    string sqlStatement = string.Format(\"TRUNCATE TABLE {0}\", tableName);
    return ExecuteNo         


        
11条回答
  •  半阙折子戏
    2020-12-16 18:55

    As far as I know, you can't use parameterized queries to perform DDL statements/ specify table names, at least not in Oracle or Sql Server. What I would do, if I had to have a crazy TruncateTable function, that had to be safe from sql injection would be to make a stored procedure that checks that the input is a table that is safe to truncate.

    
    -- Sql Server specific!
    CREATE TABLE TruncableTables (TableName varchar(50))
    Insert into TruncableTables values ('MyTable')
    
    go
    
    CREATE PROCEDURE MyTrunc @tableName varchar(50)
    AS
    BEGIN
    
    declare @IsValidTable int
    declare @SqlString nvarchar(50)
    select @IsValidTable = Count(*) from TruncableTables where TableName = @tableName
    
    if @IsValidTable > 0
    begin
     select @SqlString = 'truncate table ' + @tableName
     EXECUTE sp_executesql @SqlString
    end
    END
    

提交回复
热议问题