Home > Database > Mysql Tutorial > Can Table Names Be Parameterized in .NET/SQL for Clean and Secure Code?

Can Table Names Be Parameterized in .NET/SQL for Clean and Secure Code?

Patricia Arquette
Release: 2024-12-30 08:59:18
Original
865 people have browsed it

Can Table Names Be Parameterized in .NET/SQL for Clean and Secure Code?

Parameterizing Table Names in SQL?

Question:

Is it possible to pass table names as parameters in .NET/SQL? The end goal is to enhance the cleanliness and avoid messy code without compromising security.

Answer:

Directly parameterizing table names is not supported. However, you can indirectly achieve this using sp_ExecuteSQL:

SqlConnection conn = new SqlConnection("Your database connection string");
DataTable dt = new DataTable();

using (SqlCommand cmd = conn.CreateCommand())
{
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "sp_ExecuteSQL";

    cmd.Parameters.AddWithValue("@stmt","SELECT * FROM table");

    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
    {
        da.Fill(dt);
    }
}
Copy after login

Alternatively, you can construct the (parameterized) SQL statement in C#, appending the table name, and execute it as a command:

var name = ...; //Determine table name dynamically here
var sql = $"SELECT * FROM {"table"}";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
    cmd.Parameters.Add("", ...);
    var result = cmd.ExecuteReader();
    ...
}
Copy after login

Remember to whitelist the table names to prevent potential security vulnerabilities.

The above is the detailed content of Can Table Names Be Parameterized in .NET/SQL for Clean and Secure Code?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template