2
I’m trying to create a way to automate the business of adding parameters in the query to prevent sql inject, but it doesn’t work!
This is 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 am passing:
criarQueryComParametros("empresa", "email='teste@teste' AND senha='202CB962AC59075B964B07152D234B70'");
What happens is he’s not setting the parameters, when I give one Console.Log(query.CommandText)
, he returns:
SELECT * FROM empresa WHERE email='@p0p' AND senha='@p1p
What could I be doing wrong? Is there a better way to do this?
Have you ever thought of using one SQL Builder?
– gato
@No cat, but it seems to be exactly what I need kkk. But in case, this time I need to do it in hand. =(
– Francisco