Goal: prevent the SQL injection.
I want to pass the column name and table name as dynamically from the select query.
Consider the below method:
public bool PassColumnTableDynamic(string columnName, string tableName)
{
string commandText = string.Format(select {0} from {1}, columnName, tableName);
try
{
using (var command = new SqlCommand(commandText, _connection))
{
command.ExecuteScalar();
}
}
catch (Exception ex)
{
throw new Exception("error",ex);
}
return true;
}
The commandText is vulnerable to SQL injection. How can I prevent that?
I have the solution to create a stored procedure and pass it as parameter from this method. But I don't want to create a stored procedure.
Is there anything available in C# code to fix it?