简体   繁体   English

如何在我的Android应用程序中创建数据库?

[英]how do i create the database in my android app?

I'm trying to use SQLite in my android app. 我正在尝试在Android应用中使用SQLite。 I've created the helper class like this: 我已经创建了这样的帮助器类:

public class EventoSQLHelper {

    // Configuração da base(nome e versão)
    private static final int DB_VERSAO = 1;
    private static final String DB_NOME = "pacixDB";

    // Configuração da tabela (nome, colunas, tag para log)
    private static final String tabela_nome = "eventos";
    private static final String coluna_id = "id";
    private static final String coluna_desc = "descricao";
    private static final String coluna_data = "dataEvento";
    private static final String TAG = EventoSQLHelper.class.getSimpleName();

    // Comando sql para criação da tabela
    private static final String DATABASE_CREATE = "create table if not exists eventos (id integer primary key autoincrement, "
            + "descricao VARCHAR not null, dataEvento date);";

    // Contexto para o qual vai passar as informações
    private final Context context = null;

    private DataBaseHelper DBHelper;
    private SQLiteDatabase database;

    // Helper que extende de SQLiteOpenHelper - implementa práticas para salvar,
    // criar, etc
    private static class DataBaseHelper extends SQLiteOpenHelper {

        DataBaseHelper(Context context) {
            super(context, DB_NOME, null, DB_VERSAO);
        }

        // executado quando cria a classe: cria a base se não existir
        @Override
        public void onCreate(SQLiteDatabase db) {
            try {
                db.execSQL(DATABASE_CREATE);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // método para upgrade da base
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Atualizando base da versão " + oldVersion
                    + " para a versão " + newVersion
                    + ", que irá destruir todos os dados.");
            db.execSQL("DROP TABLE IF EXISTS eventos");
            onCreate(db);
        }
    }

    public EventoSQLHelper Open() throws SQLException {
        this.database = DBHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        DBHelper.close();
    }

    public long inserirRegistro(String descricao, String data) {
        ContentValues valoresIniciais = new ContentValues();
        valoresIniciais.put(coluna_desc, descricao);
        valoresIniciais.put(coluna_data, data);
        return database.insert(tabela_nome, null, valoresIniciais);
    }

    public boolean deletarRegistro(long id) {
        return database.delete(tabela_nome, coluna_id + " = " + id, null) > 0;
    }

    public Cursor getRegistros() {
        return database.query(false, tabela_nome, new String[] { coluna_id,
                coluna_desc, coluna_data }, null, null, null, null, null, null);
    }

I've followed some tutorials on the internet and i've understand the sqlhelper class. 我已经在互联网上关注了一些教程,并且了解sqlhelper类。 But now, how do i create the database? 但是现在,我如何创建数据库? It's a file, right? 这是文件,对不对? Do i have to create it on onCreate method of my main activity? 我是否必须在主要活动的onCreate方法上创建它?

How do i do this? 我该怎么做呢?

Well, let's quote the Docs : 好吧,让我们引用Docs

A helper class to manage database creation and version management. 一个帮助程序类,用于管理数据库创建和版本管理。

You create a subclass implementing onCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int, int) and optionally onOpen(SQLiteDatabase), and this class takes care of opening the database if it exists, creating it if it does not, and upgrading it as necessary. 您创建一个实现onCreate(SQLiteDatabase),onUpgrade(SQLiteDatabase,int,int)以及可选的onOpen(SQLiteDatabase)的子类,此类会负责打开数据库(如果存在),创建数据库(如果不存在)以及根据需要进行升级 Transactions are used to make sure the database is always in a sensible state. 事务用于确保数据库始终处于明智状态。

So what this means is, that you don't have to explicity create the "database-file" it's done for you by the SQLiteOpenHelper . 因此,这意味着您不必显式创建SQLiteOpenHelper为您完成的“数据库文件” So the first time you're opening your Database it will be created. 因此,第一次打开数据库时,它将被创建。 (It will automatically run through onCreate in your DataBaseHelper) (它将自动通过您的DataBaseHelper中的onCreate运行)

You typically use a SQLiteOpenHelper from within a ContentProvider. 通常,您可以在ContentProvider中使用SQLiteOpenHelper。

http://developer.android.com/guide/topics/providers/content-provider-basics.html http://developer.android.com/guide/topics/providers/content-provider-basics.html

The SQLite database is a file, but normally you needn't care about that. SQLite数据库是一个文件,但是通常您不需要关心它。

The database file is indeed created when the helper's onCreate method is called (assuming no exception is thrown.) Remember that, unless you uninstall the app, you shouldn't expect this method to be called again. 确实在调用助手的onCreate方法时创建了数据库文件(假定未引发任何异常。)请记住,除非卸载应用程序,否则不应期望再次调用此方法。

During the normal lifetime of an app, you'll probably provide updates and post the new version on the app store where people will either download it for the first time and install it (onCreate called) or update it (onUpgrade called ONLY if you incremented the database version number.) 在应用的正常使用期内,您可能会提供更新并将新版本发布到应用商店中,人们可以在该商店中首次下载并安装(onCreate被调用)或更新(onUpgrade仅当您递增时才更新)数据库版本号。)

Since the Google play store currently doesn't provide a way to allow users to go back to an older version of your app, you typically don't have to worry about onDowngrade. 由于Google Play商店目前尚不提供允许用户返回到您应用的较旧版本的方法,因此您通常不必担心onDowngrade。 If, however, you are providing older versions of your app outside of the Google play store, you should at least override onDowngrade so it doesn't throw a SQLiteException which is what the default implementation does. 但是,如果您要在Google Play商店之外提供较旧版本的应用,则至少应重写onDowngrade,以便它不会引发SQLiteException异常(默认实现会如此)。

Now, back to onUpgrade. 现在,回到onUpgrade。 Some things you might need to do here are add a table, modify an existing table, drop a table, etc. I have handled this by writing .sql scripts that I put in the assets folder of my app with a name like upgrade_v1_v2.sql. 您在此处可能需要做的一些事情是添加表,修改现有表,删除表等。我已经通过编写.sql脚本(使用我的应用程序的Assets文件夹中的.sql脚本,例如upgrade_v1_v2.sql之类的名称)来处理此问题。 。

There are some gotchas with SQLite you should be aware of that are detailed here: 您应该了解SQLite的一些陷阱,在这里进行了详细说明:

http://www.sqlite.org/omitted.html http://www.sqlite.org/omitted.html

There are usually workarounds, however. 但是,通常有解决方法。 For example, if you wanted to add a new column with a foreign key constraint to an existing table, you can't use the ALTER TABLE command for this since it is currently not supported by SQLite. 例如,如果要向现有表中添加具有外键约束的新列,则不能为此使用ALTER TABLE命令,因为SQLite当前不支持该命令。 Instead, you'll have to make a temporary table with the new set of columns you want, then copy the data from the old table to this temporary table, then drop the old table, and finally rename the temporary table to the old table's name - all preferably within a transaction to guard against something going wrong halfway through. 取而代之的是,您必须使用所需的新列集创建一个临时表,然后将数据从旧表复制到此临时表,然后删除旧表,最后将临时表重命名为旧表的名称。 -所有这些交易都最好在交易中进行,以防中途出错。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何创建在线数据库并将其连接到 Android 应用程序? - How do i create an online database and connect it to an android app? 我如何获取连接到实时 firebase 数据库的 android 应用程序以在实时数据库中更新时创建吐司? - how do i get my android app which is connected to a realtime firebase database to create a toast on update in the realtime database? 如何将我的Android应用程序连接到远程MySQL数据库? - How do I connect my Android app to a remote MySQL database? 如何创建我的Android应用程序的Amazon版本? - How do I create an Amazon version of my android app? 如何为我的Android应用程序创建全局高分? - How do I create a global high score for my android app? Android-如何创建我的应用的另一个版本? - Android - how do I create another version of my app? 如何为我的Android应用程序创建自定义可点击的图形? - How do i create a custom clickable graphic for my android app? 如何在Android中为我的应用创建临时数据库? - How to create a temp database for my app in Android? 如何在 Android 中创建/打开数据库? - How do I create/open a database in Android? 如何将数据库连接到 Android 应用程序? - How do I connect a database to an Android app?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM