-2
I have the following code snippet:
using(MySqlConnection conn = new MySqlConnection(conexao)){
try
{
string consulta = "SELECT * FROM tb_Cliente WHERE ID_Cliente IN ("+listaClientes+")";
MySqlCommand cmd = new MySqlCommand(consulta,conn);
conn.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
using(MySqlConnection conn2 = new MySqlConnection(conexao))
{
try
{
consulta = "INSERT INTO tb_Teste (ID_Cliente,Nome_Cliente,Idade_Cliente,Data_Insert) VALUES (@ID_Cli,@Nome_Cli,@Idade_Cli,@Data_insert)";
MySqlCommand cmd2 = new MySqlCommand(consulta,conn2);
cmd2.Parameters.AddWithValue("@ID_Cli",reader["ID_Cliente"]);
cmd2.Parameters.AddWithValue("@Nome_Cli",reader["Nome_Cliente"]);
cmd2.Parameters.AddWithValue("@ID_Cli",reader["ID_Cliente"]);
cmd2.Parameters.AddWithValue("@Idade_Cli",reader["Idade_Cliente"]);
cmd2.Parameters.AddWithValue("@Data_insert",DateTime.Now);
conn2.Open();
cmd2.ExecuteNonQuery();
conn2.Close();
}
catch(MySqlException ex)
{
EscreverLog("ERRO: " + ex.Message);
}
}
}
}
catch(MySqlException ex)
{
EscreverLog("ERRO: " + ex.Message);
}
finally
{
conn.Close();
}
}
In it I do a SELECT searching all clients in the range specified by the string listClientes and for each result I do an INSERT in another table, with other information more.
Running the code everything works normal but I think it’s wrong to open several Mysqlconnection and Mysqlcommands. How can I change the code to make it less "messy"? For example using the same connection or even the same Command.
listaCliente
is just a string with client ids, for example: if the listClientes = "1,3,5", SELECT only looks for clients with IN 1,3,5 ids. Thank you().– Fabio Hagiwara