In C# I have the following function:
public bool Set(int id, string columnName, object value)
{
/// <summary>
/// This function sets the given column name to the given value for the given id.
/// Returns true if the operation was successful, false otherwise.
/// </summary>
string query = "UPDATE " + TableName + " SET " + columnName + " = @value WHERE id = @id";
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
command.Parameters.AddWithValue("@id", id);
....
I cannot set columnName
as an parameter, that does not work. However the column name should be a user input. How can I make this sanitize?
I tried making columnName
an variable like this @columnName
and setting it later, however, this does not work because I think SQL Server interprets this as a string later, not a column object.
2条答案
按热度按时间dpiehjr41#
I felt like writing something for this anyway, because I don't write a lot of C#. I do, however, want to repeat that everything in the comments is still true; just don't do this.
That being said, what you can do if pass parameters for the object names, the id and the value, and then create a dynamic SQL statement, checking against the system objects. This results in some (awful abomination) like this:
jyztefdp2#
A simple way to "sanitize" your input is to try to find the table name and column names in the system tables and do it using a parametrized query.
disclaimer: I'm not a big fan of doing things the way you are doing nor doing stuff that needs sanitized user inputs. You need to question those things first.