Java command to add column to table [closed]

-2

I need the Java code on Android to do the column sum of a particular SQLite table.

I know the command is " Select sum(coluna) from tabela ", but what I need to know is how to write this in Java to be able to retrieve this value from the sum.

As the column is about numbers, some command returns an integer value that I might be using elsewhere. Thanks in advance.

    
asked by anonymous 14.07.2016 / 04:54

1 answer

1

Apparently you need to access a table column, but I can not say exactly what kind of component you are using, so my best suggestion is to use EntityManager of JPA.

Start by creating a class that will open the connection to the bank, as in the example below.

private static ConnectionFactory instance;
private final EntityManagerFactory factory;

private ConnectionFactory() {
    factory = Persistence.createEntityManagerFactory("nome da persistence unit"));
}

private EntityManager getEntityManager() {
    return factory.createEntityManager();
}

public static EntityManager getConnection() {
    if (instance == null) {
        instance = new ConnectionFactory();
    }

    return instance.getEntityManager();
}

After this, create an Entity class, which will be responsible for receiving the data retrieved from the table by another class that accesses the database, for example: "SOMA".

And finally create the data access class and use a Query to retrieve the column data of the table you want to sum.

public Integer soma() {
    EntityManager em = getEntityManager();
    em.getTransaction().begin();

    Query q = em.createQuery("SELECT sum(coluna) from tabela");

    Integer soma = (Integer) q.getSingleResult();

    em.getTransaction().commit();
    em.close();

    return soma;
}

EDIT 1

Here is the code for a SELECT command in the SQLite database that can be used on Android systems. See this question: Android SQLite SELECT

SQLiteDatabase db = this.getReadableDatabase();
    Cursor c = db.rawQuery("SELECT sum(column1) FROM table ", null);
    if(c.moveToFirst()){
        do{
           //Recuperando valores 
           int column1 = c.getInt(0);

    //Fazendo algo com os valores

        }while(c.moveToNext());
    }
    c.close();
    db.close();
    
15.07.2016 / 19:01