简体   繁体   English

SQLiteOpenHelper - 数据库是如何创建的?

[英]SQLiteOpenHelper - how is the database created?

I'm making a database application, and my program works and I've understood most of the tutorial I've been following. 我正在制作一个数据库应用程序,我的程序正常工作,我已经理解了我一直关注的大部分教程。 However, one aspect remains unclear to me. 但是,有一方面我不清楚。

There is an inner class of MyDBHelper extending SQLiteOpenHelper. 有一个内部类的MyDBHelper扩展了SQLiteOpenHelper。 Outer variables include the SQLiteDatabase called d. 外部变量包括名为d的SQLiteDatabase。 The code for the MyDBHelper is: MyDBHelper的代码是:

private static class MyDBHelper extends SQLiteOpenHelper {
        MyDBHelper(Context c) {
            super(c, DB_NAME, null, DB_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            try {
                db.execSQL(DATABASE_CREATE);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVers, int newVers) {
            Log.w(TAG, "Upgrading database from version " + oldVers + " to " + newVers + ", which will destroy all old data.");
            db.execSQL("DROP TABLE IF EXISTS GM");
            onCreate(db);
        }
    }

My question is how does this actually create the initial database. 我的问题是这是如何实际创建初始数据库的。 It occurs in the onCreate() method, but as far as I can see, this is never called. 它出现在onCreate()方法中,但据我所知, 从未调用过。 I understand that it is called when the database is created for the first time, but where? 我知道它是在第一次创建数据库时调用的,但在哪里? And furthermore, how is it passed a SQLiteDatabase db? 而且,它如何通过SQLiteDatabase数据库? I haven't passed any database to the method. 我还没有将任何数据库传递给该方法。 And how is my SQLiteDatabase db variable from the outer class set to the created database? 我的SQLiteDatabase db变量如何从外部类设置为创建的数据库? Could someone talk me through this like an idiot? 有人能像白痴一样跟我说话吗?

onCreate() and onUpgrade() methods are really called the first time when Db is created. onCreate()onUpgrade()方法实际上是在创建Db时第一次调用的。 In facts, it's checked in getReadableDatabase() or getWritebleDatabase() methods of SQLiteOpenHelper . 在事实,它已选中getReadableDatabase() or getWritebleDatabase()方法SQLiteOpenHelper It will check if the DB already exist on the data directory and what is it's version. 它将检查数据库目录中是否已存在DB以及它的版本是什么。 According to this it will either call onCreate(), or onUpgrade() . 根据它,它将调用onCreate(), or onUpgrade() Or nothing, if db file exist and of correct version. 如果db文件存在且版本正确,则不执行任何操作。

You can search your code for executing myDBHelper.getReadable(Writable)Database() . 您可以搜索代码以执行myDBHelper.getReadable(Writable)Database() That is the time when this check will be performed. 这是执行此检查的时间。

Please let me know if more details are needed. 如果需要更多详细信息,请与我们联系。 Good luck 祝好运

Keep in mind that you are extending SQLiteOpenHelper, all of the magic happens in this super class, specifically the database is initially created (or just re-opened) when you call either getReadableDatabase() or getWritableDatabase() . 请记住,您正在扩展SQLiteOpenHelper,所有这些神奇都发生在这个超类中,特别是当您调用getReadableDatabase()getWritableDatabase()时,最初创建(或只是重新打开)数据库。 These two methods: 这两种方法:

  • Define the SQLiteDatabase db variable (and control passing db to your callback methods) 定义SQLiteDatabase db变量(并控制将db传递给回调方法)
  • Initialize db by calling your onCreate(db) method or opening the existing database 通过调用onCreate(db)方法或打开现有数据库来初始化db
  • Check the version number and call your onUpgrade(db) or onDowngrade(db) if necessary 检查版本号,并在必要时调用onUpgrade(db)onDowngrade(db)

They also call a few more callback methods like onConfigure(db) , onOpen(db) , etc. ( Read more about these methods.) If it will help, you can read through the source code yourself to understand the structure of how and when all of this happens. 他们还调用了一些回调方法,如onConfigure(db)onOpen(db)等。( 阅读更多关于这些方法的内容。)如果有帮助,你可以自己阅读源代码 ,了解如何以及何时的结构所有这一切都发生了。

The onCreate() method is not a constructor for this class. onCreate()方法不是此类的构造函数。 onCreate is called when you create the DB. 创建数据库时会调用onCreate。

Here PeopleDB extends SQLiteOpenHelper. 这里PeopleDB扩展了SQLiteOpenHelper。 This code is from a different class and onCreate is called when getWritableDatabase() or getReadableDatabase(), or anything of the sort is called 此代码来自不同的类,当调用getWritableDatabase()或getReadableDatabase()或调用任何类型时调用onCreate

  PeopleDB db = null; //onCreate NOT called here
  db=new PeopleDB(getContext());
  db.getWritableDatabase();  //onCreate is called here!

Hope that helps. 希望有所帮助。

See our database is created in the openhelper's constructor itself not in the overridden onCreate method. 请参阅我们的数据库是在openhelper的构造函数中创建的,而不是在重写的onCreate方法中创建的。 Inside onCreate method we are firing a query for creating a table in the database which is created in open helper's constructor to insert the data not creating the database. 在onCreate方法中,我们将触发一个查询,用于在数据库中创建一个表,该表是在open helper的构造函数中创建的,用于插入不创建数据库的数据。

One more thing is SQLiteDatabase object is not instantiated in SQLiteOpenHelper class. 还有一件事是SQLiteDatabase对象没有在SQLiteOpenHelper类中实例化。 It is instantiated in the class where you want to use the database to perform db operations and there you need to write a function like this to intialise or open your database to get ready for insertion. 它在您要使用数据库执行数据库操作的类中实例化,您需要编写这样的函数来初始化或打开数据库以准备插入。

SQLiteDatabase database;

YourOpenHelper yourOpenHelper=new YourOpenHelper(); //to creating database using openhelper and automatically call onCreate to make a table in that

    public void open() throws SQLException {
            database = profiloHelper.getWritableDatabase();
        }

Here is code you have to write for any operation in database like insertion deletion anything, you just have to change the QUERY 以下是您必须为数据库中的任何操作编写的代码,例如插入删除任何内容,您只需更改QUERY即可

SQLiteStatement insert_stmt = null;

        try {
            insert_stmt = database.compileStatement(YOUR_QUERY);

            insert_stmt.bindString(1,   field1);
            insert_stmt.bindString(2,   field2);
            insert_stmt.executeInsert();
        }
        finally {
            if (insert_stmt != null) insert_stmt.close();
        }

可能是在getReadableDatabase()getWriteableDatabase()中第一次调用它们时


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)的子类,如果数据库存在,该类负责打开数据库,如果不存在则创建数据库,并根据需要进行升级。 。 (Android Developer Website) (Android开发者网站)

The class SQLiteOpenHelper is called "Helper" for good reason. SQLiteOpenHelper类有充分的理由称为“Helper”。 It saves us app writers considerable effort. 它为我们的应用编写者节省了相当大的努

The first time that you call getWritableDatabase (or getReadableDatabase ) for your implementation of SQLiteOpenHelper , your super statement in your constructor passes the current Context and the database NAME that you prefer to the superclass constructor for SQLiteOpenHelper . 第一时间致电getWritableDatabase (或getReadableDatabase )为您实现SQLiteOpenHelper ,你super在构造函数语句将当前Context和数据库NAME ,你喜欢的父类的构造SQLiteOpenHelper

The superclass constructor then sets up initial space for your SQLiteDatabase and assigns it the name that you passed through super . 然后,超类构造函数为SQLiteDatabase设置初始空间,并为其指定通过super传递的名称。

When finished, the superclass constructor calls onCreate and passes the named SQLiteDatabase that it created through onCreate 's only parameter. 完成后,超类构造函数调用onCreate并传递它通过onCreate唯一参数创建的命名SQLiteDatabase Since onCreate only gets called this one time, it's a very good place to call execSQL to define the structure of your database. 由于onCreate只被调用一次,因此它是调用execSQL来定义数据库结构的一个非常好的地方。

Subsequent executions of getReadableDatabase (or getWritableDatabase ) merely open the database for you and never again call onCreate . getReadableDatabase (或getWritableDatabase )的后续执行只是为您打开数据库,而不再调用onCreate (When the superclass constructor notes that super has sent a different version number, onUpgrade is calle.) (当超类构造函数注意到super发送了不同的版本号时, onUpgrade是calle。)

Understanding the way SQLiteOpenHelper creates a database without obvious code and how the heck onCreate gets passed an argument "out of the blue" was a real chore for me. 理解SQLiteOpenHelper在没有明显代码的情况下创建数据库的方式以及heck onCreate如何通过“突然出现”的参数传递给我一个真正的苦差事。 Now I can't believe it could have ever been hard. 现在我无法相信它可能会变得艰难。

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

相关问题 Android | SQLLite:不使用SQLiteOpenHelper预先创建的数据库更新 - Android | SQLLite : Pre-created database updating without using SQLiteOpenHelper 如何创建只有两列的简单数据库并在Android中使用它? (使用SQLiteOpenHelper) - How to create simple database with only 2 columns and use it in Android? (using SQLiteOpenHelper) Android-SQLiteOpenHelper-如何将图像直接存储到数据库 - Android - SQLiteOpenHelper- how to store images directly to database 如何使用 SQliteOpenhelper :android 项目将 SQLite 数据库路径更改为不同的文件夹(在应用程序目录中) - How to change SQLite database path to different folder (in application directory) using SQliteOpenhelper :android project 如何将SQLiteOpenHelper类与MainActivity连接? - How to connect SQLiteOpenHelper class with MainActivity? 如何在自定义适配器中分配SQLiteOpenHelper? - How to assign SQLiteOpenHelper in Custom Adapter? SQLiteOpenHelper如何返回SQLiteDatabase? - How can SQLiteOpenHelper return SQLiteDatabase? 如何从SQLiteOpenHelper访问StartActivityForResult()? - How to access StartActivityForResult() from SQLiteOpenHelper? SQLiteOpenHelper不会从资产安装数据库文件 - SQLiteOpenHelper does not install database file from assets 在主活动中使用SQLiteOpenHelper类访问数据库 - Database using SQLiteOpenHelper Class accessing in main activity
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM