List last record inserted in Mysql c #

0

I need to get the last data inserted depending on a search.

foreach (DataGridViewRow row in dgvDispositivos.Rows)
{
  string dispositivo = row.Cells[1].Value.ToString();
  //Aqui hago la consulta dependiendo del usuario en el ciclo:
  bd.ejecutarConsulta("SELECT dispositivo,latitud,longitud FROM dispositivos WHERE dispositivo='"+dispositivo+"'");
}

Since many routes have been traced in the table with that device, I only want to extract the last data that was inserted from it.

    
asked by DoubleM 13.12.2016 в 09:12
source

3 answers

3

To know which is the last record inserted you have two options:

  • Create a self-incremental field in MySQL, such as:

    CREATE TABLE table_name
    (
        id INTEGER AUTO_INCREMENT PRIMARY KEY
    )
    
  • Create a field of type date.

  • If you use the first option, you do the search taking into account that the id is the largest that meets the conditions of your search (the device).

    If you use the second option, do the search keeping in mind that the date is the largest that meets the conditions of your search (the device).

        
    answered by 13.12.2016 в 09:44
    2

    Let's start from the base that this method that you show in the code is incorrect, you should NEVER build a query by concatenating the values in a string, you have to use parameters.

    In addition, the code should return something if it is a SELECT, be it a list, collection or datatable with the records that you get from the select

    foreach (DataGridViewRow row in dgvDispositivos.Rows)
    {
        string dispositivo = row.Cells[1].Value.ToString();
    
        DataTable dt = bd.ObtenerDispositivos(dispositivo);
    
        //resto codigo
    }
    
    
    
    public DataTable ObtenerDispositivos(string dispositivo)
    {
        DataTable dt = new DataTable();  
        using (SqlConnection conn = new SqlConnection("connection string"))  
        {  
            string query = "SELECT dispositivo,latitud,longitud FROM dispositivos WHERE dispositivo = @dispositivo";  
    
            SqlCommand cmd = new SqlCommand(query, conn);  
            cmd.Parameters.AddWithValue("@dispositivo", dispositivo);  
    
            SqlDataAdapter da = new SqlDataAdapter(cmd);    
            da.Fill(dt);  
        } 
    
        return dt;
    } 
    

    As you can see, the idea is to indicate the device and not the select so that we can define the query parameter

        
    answered by 13.12.2016 в 10:47
    2

    Well the query that helps you with what you need is

    SELECT TOP 1 dispositivo,latitud,longitud FROM dispositivos WHERE dispositivo = @dispositivo ORDER BY id DESC
    

    As it says @LeandroTuttini does not concatenate string and values, it takes parameters

        
    answered by 13.12.2016 в 17:01