Java command to add column in table

Asked

Viewed 878 times

-2

I need the code in Java on Android to sum the column of a given 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 recover this sum value.

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

1 answer

1

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

Start by creating a class that will open the connection to the database, 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 that, create an Entity class, which will be responsible for receiving the recovered table data by another class accessing the database, example: "Summed".

And finally create the data access class and use a Query to recover the data from the table column you want to carry out the 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();
  • Friend, thanks for the answer. The query no longer works in my java project. It is for android platform, and the sqlite commands I believe q are different.

  • Added part of code that works on Sqlite in response.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.