I'm trying to create a way to automate the business of adding parameters in the query to prevent sql inject, but it does not work!
Here's my code:
public static MySqlCommand criarQueryComParametros(string tabela, string condicao)
{
List<string> parametros = Regex.Split(condicao, "'(.*?)'").ToList();
parametros = parametros.Where(x => parametros.IndexOf(x) % 2 == 1).ToList();
string sql = "SELECT * FROM " + tabela + " WHERE " + remodelarCondicao(condicao, parametros);
MySqlCommand query = new MySqlCommand(sql, Database.conexao);
montarListaDeParametros(condicao, parametros, query);
return query;
}
public static void montarListaDeParametros(string condicao, List<string> parametros, MySqlCommand query)
{
for (int i = 0; i < parametros.Count; i++)
{
query.Parameters.AddWithValue($"@p{i}p", parametros[i]);
}
}
public static string remodelarCondicao(string condicao, List<string> parametros)
{
for (int i = 0; i < parametros.Count; i++)
{
condicao = condicao.Replace(parametros[i], $"@p{i}p");
}
return condicao;
}
Parameters I'm passing:
criarQueryComParametros("empresa", "email='teste@teste' AND senha='202CB962AC59075B964B07152D234B70'");
What happens is that it is not setting the parameters, when I give Console.Log(query.CommandText)
, it returns:
SELECT * FROM empresa WHERE email='@p0p' AND senha='@p1p
What can I be doing wrong? Is there any better way to do this?