MySql query from a page on asp.net

0

I'm trying to implement this code snippet

public List<int> Temperatura()
        {
            List<int> Datos = null;
            string connStr = "server=localhost;user=root;database=sensores;port=3306;password=123456;";
            MySqlConnection conn = new MySqlConnection(connStr);
            try
            {
                Console.WriteLine("Connecting to MySQL...");
                conn.Open();

                string sql = "Select temperatura From datos where fecha  between '" + Label3.Text + "' and '" + Label4.Text + "';";
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                MySqlDataReader rdr = cmd.ExecuteReader();

                while (rdr.Read())
                {

                    Datos.Add(Convert.ToInt32(rdr[0]));
                }
                rdr.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            conn.Close();
            Console.WriteLine("Done.");
            return Datos;

but when loading the list, it skips that part and does not bring all the data, I do not know if it's the getValue or how it should attach the data

    
asked by Sebastian Mateus Villegas 15.11.2016 в 05:46
source

1 answer

1

If the field fecha in the database is DateTime , it does not make sense that in the query you pass the date as string. Try this:

DateTime fecha1=DateTime.Parse(Label3.Text);
DateTime fecha2=DateTime.Parse(Label4.Text);
string sql = "Select temperatura From datos where fecha between @fecha1 and @fecha2";
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@fecha1", fecha1);
cmd.Parameters.AddWithValue("@fecha2", fecha2);

In this way, on the one hand you use a parameterized query that will avoid the possibility of a sql injection, and on the other you pass a datetime to the query that is what is really expected.

    
answered by 15.11.2016 в 10:33