How to make Inserts in table creation in Sqlite?

Asked

Viewed 137 times

1

I would like to know how to do INSERT manuals in the Databasehelper class that extends from Sqliteopenhelper.

public class DatabaseHelper extends SQLiteOpenHelper {

private static final String BANCO_DADOS = "Agenda";
private static int VERSAO = 1;


public DatabaseHelper(Context context) {
    super(context, BANCO_DADOS, null, VERSAO);
}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL( "CREATE TABLE amigo (_id INTEGER PRIMARY KEY," +
                " nome TEXT, telefone TEXT, " +
                " email TEXT, categoria INTEGER);"
    );
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

}

What I wanted was to make Inserts within the onCreate method of the Databasehelper class just as the table was created, but I don’t know how to do.

  • Welcome to Stack Overflow. Try to ask one question at a time. It is better to answer and to consult later.

1 answer

0


You can do INSERT the same way you did with CREATE, passing the SQL command in the execSQL function.

It is not recommended to make SQL queries directly from the application. The ideal is to work with content providers (Content Providers) who act as a layer of abstraction between the database and the application, making the database more isolated and easier to implement evolutions or sharing data with other applications.

Also, if you are going to use lists (Recyclerview) to present the data using a Loader to manage it, the use of Content Provider is essential.

More details here about Content Providers: https://developer.android.com/guide/topics/providers/content-providers.html?hl=pt-br

  • Thank you for answering, I understood the part of INSERT in the execSQL function. But and to make queries with INNER JOIN or queries that need 2 or more parameters. How do I?

  • As I said before, the ideal is to always access the database using Content Provider and its method for query in the database is "query()" which receives a single table as a parameter. Since you want to do an INNER JOIN between 2 tables, so as not to complicate too much, I would create a VIEW in the database making the INNER JOIN necessary and then pass this view in the query method I mentioned above. There are other methods, but I believe this to be simpler.

Browser other questions tagged

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