简体   繁体   中英

Using SqlParameter for security with C# ASP.NET and SQL Server 2008 R2

I'm converting the following C# markup to use SqlParameter (I'm new to SqlParameter) in order to enhance security:

public static void EmptyTable(string TableToEmpty)
{
    try
    {
        using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand("TRUNCATE TABLE @prmTableToEmpty", conn))
            //using (SqlCommand cmd = new SqlCommand("TRUNCATE TABLE " + TableToEmpty, conn))
            {
                cmd.Parameters.Add(new SqlParameter("@prmTableToEmpty", TableToEmpty));
                cmd.Connection.Open();
                cmd.ExecuteNonQuery();
            }
        }
    }
    catch
    {
        throw;
    }
}

without the parameter use it works smoothly. However, with this syntax I get this exception:

    [SqlException (0x80131904): Incorrect syntax near '@prmTableToEmpty'.]
   System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +2073550
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +5064508
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() +234
   System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2275
   System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +215
   System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +987
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +162
   System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) +178
   System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +137
   pjsql.EmptyTable(String TableToEmpty) in c:\website\App_Code\mySqlClass.cs:67
   _Default.btnEmptyTheTable_Click(Object sender, EventArgs e) in c:\website\Default.aspx.cs:83
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +118
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563

both line numbers mentioned contains the throw; command.

I went through this: http://msdn.microsoft.com/en-us/library/4f844fc7(v=vs.71).aspx

and tried this alternative syntax: http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson06.aspx

but with no luck.

What am I missing?

Parameters may not be used in place of object names.

To enhance secutiry when dynamically substituting object names, use quotename (first execute a command select quotename(@prmTableToEmpty) using a parameter, then use the result of this command to build your truncate comand and execute it without parameters).

using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
    conn.Open();

    string sanitized_name;

    using (SqlCommand cmd = new SqlCommand("select quotename(@prmTableToEmpty)", conn))
    {
        cmd.Parameters.Add(new SqlParameter("@prmTableToEmpty", TableToEmpty));
        sanitized_name = (string)cmd.ExecuteScalar();
    }

    using (SqlCommand cmd = new SqlCommand("TRUNCATE TABLE " + sanitized_name, conn))
    {
        cmd.ExecuteNonQuery();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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