如何创建在我的Andr​​oid应用程序的数据库? [英] how do i create the database in my android app?

查看:89
本文介绍了如何创建在我的Andr​​oid应用程序的数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用SQLite在我的Andr​​oid应用程序。我已经创建了辅助类是这样的:

I'm trying to use SQLite in my android app. 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);
    }

我已经试过了网上一些教程,我已经了解提供SQLHelper类。但现在,我怎么创建数据库?这是一个文件,对不对?我必须对我的主要活动onCreate方法创建它?

I've followed some tutorials on the internet and i've understand the sqlhelper class. 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?

我如何做到这一点?

推荐答案

好了,让我们引用的文档

一个辅助类来管理数据库的创建和版本管理。

A helper class to manage database creation and version management.

您创建一个子类实现的onCreate(SQLiteDatabase)   onUpgrade(SQLiteDatabase,INT,INT)和任选   的OnOpen(SQLiteDatabase),这个类的需要打开的护理   数据库,如果它存在,创建它,如果它不,升级作为   必要。交易被用来确保数据库总是   在一个合理的状态。

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. Transactions are used to make sure the database is always in a sensible state.

所以,这是什么意思是,你不必明确地创建的数据库文件的它是由 SQLiteOpenHelper 。所以第一次你打开你的数据库将被创建。 (它会自动通过的onCreate 在DataBaseHelper运行)

So what this means is, that you don't have to explicity create the "database-file" it's done for you by the SQLiteOpenHelper. So the first time you're opening your Database it will be created. (It will automatically run through onCreate in your DataBaseHelper)

这篇关于如何创建在我的Andr​​oid应用程序的数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆