SqlParameter does not allows Table name - other options without sql injection attack?

半腔热情 提交于 2019-11-26 11:28:07

问题


I got a runtime error saying \"Must declare the table variable \"@parmTableName\". Meaning having table name as sql parameter in the sql-statement is not allowed.

Is there a better option or suggestion than allowing sql injection attack? I don\'t want to do this C# script for sql statement \" DELETE FROM \" + tableName + \" \";

using(var dbCommand = dbConnection.CreateCommand())
{
   sqlAsk = \"\";
   sqlAsk += \" DELETE FROM @parmTableName \";
   sqlAsk += \" WHERE ImportedFlag = \'F\' \";

   dbCommand.Parameters.Clear();
   dbCommand.Parameters.AddWithValue(\"@parmTableName\", tableName);

   dbConnection.Open();

   rowAffected = dbCommand.ExecuteNonQuery();
}

回答1:


Go for a white list. There can only be a fixed set of possible correct values for the table name anyway - at least, so I'd hope.

If you don't have a white list of table names, you could start with a whitelist of characters - if you restrict it to A-Z, a-z and 0-9 (no punctuation at all) then that should remove a lot of the concern. (Of course that means you don't support tables with odd names... we don't really know your requirements here.)

But no, you can't use parameters for either table or column names - only values. That's typically the case in databases; I don't remember seeing one which did support parameters for that. (I dare say there are some, of course...)




回答2:


As others have already pointed out that you can't use Table Name and Fields in Sql Parameter, one thing that you can try is to escape table name using SqlCommandBuilder, like:

string tableName = "YourTableName";
var builder = new SqlCommandBuilder();
string escapedTableName = builder.QuoteIdentifier(tableName);

using (var dbCommand = dbConnection.CreateCommand())
{
    sqlAsk = "";
    sqlAsk += " DELETE FROM " + escapedTableName; //concatenate here
    sqlAsk += " WHERE ImportedFlag = 'F' "; 

    dbCommand.Parameters.Clear();

    dbConnection.Open();

    rowAffected = dbCommand.ExecuteNonQuery();
}



回答3:


(sqlAsk is string, right?) if it's right so let's try this:

using(var dbCommand = dbConnection.CreateCommand())
{
   sqlAsk = "";
   sqlAsk += " DELETE FROM <table_name> ";
   sqlAsk += " WHERE ImportedFlag = 'F' ";

   string table_name = "Your table name here";  //<- fill this as u need 
   sqlAsk = sqlAsk.Replace("<table_name>", table_name); // it will replace <table_name> text to string table_name

   dbConnection.Open();

   rowAffected = dbCommand.ExecuteNonQuery();
}


来源:https://stackoverflow.com/questions/17947736/sqlparameter-does-not-allows-table-name-other-options-without-sql-injection-at

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!