Wang Liping-simple application of SQLite, SQLiteOpenHelper, and sqliteopenhelper

Source: Internet
Author: User

Wang Liping-simple application of SQLite, SQLiteOpenHelper, and sqliteopenhelper

The Android platform provides a database helper class to create or open a database. This helper class inherits from the SQLiteOpenHelper class. In the constructor of this class, call the method in Context to create and open a database object with the specified name. The main task of inheriting and extending the SQLiteOpenHelper class is to rewrite the following two methods.

Public class MySQLiteHelper extends SQLiteOpenHelper {
Public MySQLiteHelper (Context context, String name, CursorFactory factory,
Int version ){
Super (context, name, factory, version );
// TODO Auto-generated constructor stub
}
// This method is executed when the database is created for the first time. Generally, the initialization tasks such as table creation are put here.
// ExecSQL creates a table
@ Override
Public void onCreate (SQLiteDatabase db ){
// TODO Auto-generated method stub
// Create a table
String SQL = "create table if not exists hero_info (" + "id integer primary key," + "name varchar," + "level integer )";
Db.exe cSQL (SQL );
}
@ Override
Public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion ){
// TODO Auto-generated method stub

}

MainActivity. java

Package com. example. sqllite;
Import android. app. Activity;
Import android. content. ContentValues;
Import android. database. Cursor;
Import android. database. sqlite. SQLiteDatabase;
Import android. graphics. Color;
Import android. OS. Bundle;
Import android. widget. TextView;
Public class MainActivity extends Activity {
Private TextView TV;
Private MySQLiteHelper h;


@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_main );
Init ();
}
Public void init (){
TV = (TextView) findViewById (R. id. TV );
H = new MySQLiteHelper (this, "my. db", null, 1 );
InsertAndUpdateData (h );
// Query data
String result = queryData (h );
TV. setTextColor (Color. RED );
TV. setTextSize (20366f );
TV. setText ("Name \ t Level \ n" + result );


}

 
Private void insertAndUpdateData (MySQLiteHelper helper ){
// TODO Auto-generated method stub

// The getReadableDatabase method does not always return read-only database objects,
// Generally, this method returns the same result as the getWriteableDatabase method,
// A read-only database object is returned only when the database is only available for read-only or when the disk is full.

SQLiteDatabase db = helper. getWritableDatabase ();
// Insert data to the table using the execSQL Method
Db.exe cSQL ("insert into hero_info (name, level) values ('bb', 0 )");
// Insert data into the table using the insert method
ContentValues values = new ContentValues ();
Values. put ("name", "xh ");
Values. put ("level", 5 );
// Call the method to insert data
Db. insert ("hero_info", "id", values );
// Use the update method to update table data
// Clear the ContentValues object
Values. clear ();
Values. put ("name", "xh ");
Values. put ("level", 10 );
// Update the xh level to 10.
Db. update ("hero_info", values, "level = 5", null );
// Close the SQLiteDatabase object
Db. close ();

}
// Query data from the database
Public String queryData (MySQLiteHelper myHelper ){
String result = "";
// Obtain the database object
SQLiteDatabase db = myHelper. getReadableDatabase ();
// Query the data in the table
Cursor cursor = db. query ("hero_info", null, "id asc ");
// Obtain the index of the name column
Int nameIndex = cursor. getColumnIndex ("name ");
// Obtain the index of the level column
Int levelIndex = cursor. getColumnIndex ("level ");
For (cursor. moveToFirst ();! (Cursor. isAfterLast (); cursor. moveToNext ()){
Result = result + cursor. getString (nameIndex) + "\ t ";
Result = result + cursor. getInt (levelIndex) + "\ n ";
}
Cursor. close (); // close the result set.
Db. close (); // close the database object
Return result;
}
@ Override
Protected void onDestroy (){
SQLiteDatabase db = h. getWritableDatabase (); // obtain the database object
// Delete all data in the hero_info table. Input 1 to delete all rows. ------> click back.
Db. delete ("hero_info", "1", null );
Super. onDestroy ();
}
}



In Android development, why should I use SQLiteOpenHelper to obtain a SQLiteDatabase database and then perform operations on the database?

Do you know the singleton mode? His design philosophy is to use the singleton mode. When you use databases in multiple places, only one connection is provided for you, which prevents conflicts and improves performance.

How to Use SQLite

Here are some of Kevin's experiences on his use. The original Article roughly means that the Android example covers some basic usage of Sqlite, however, they did not provide a reasonable method of use in depth, and more importantly, they did not provide a reasonable method of use. Most examples and documents only involve the most basic database queries, or teach you how to create a ContentProvider. What is never mentioned here is: · where can I create and save a SQLiteOpenHelper instance? · How many instances can be created? · Is there anything to worry about accessing the database with multiple threads? The basic content is that you can connect to the Sqlite database any number of times, and the Android system also supports you. Sqlite has a file-Level Lock for Synchronous access and error prevention. If you only know this, it will bring you great pain. One advantage of open source is that you can go deep into the code. From code and some tests, I learned the fact that Sqlite has a file-Level Lock. Many threads can read data at the same time, but only one thread can write data. The lock prevents multiple concurrent writes. · Android implements some java locks in SQLiteDatabase to ensure that the action is synchronized. · If you use multiple threads to access the database, your database will not (or should not) Crash. It is not mentioned that if you write a database through multiple different real connections, one of them will fail, and it will not continue writing after the previous one is completed. In a simple way, it won't write your changes. Worse, you won't get an exception, but it just outputs some messages in LogCat. That's all. SQLiteOpenHelper class has done some interesting things. Although it can obtain a read-only connection and a read-write connection, they are essentially the same connection. If there is no file write error, the read-only connection is essentially a read/write connection. Interesting. Therefore, if your app uses a helper, you will never use multiple connections Even if you use it in multiple threads. Similarly, there is only one SQLiteDatabase instance in a helper instance, and some java locks are implemented in this instance. Therefore, when you are performing database operations, other db operations will be locked. Even if you use multiple threads to do these tasks to optimize database performance, bad messages are useless. According to my understanding, the way SQLite works is basically impossible to destroy your database, unless there are bugs in the code or hardware problems. Therefore, we recommend that you create a static SQLiteOpenHelper object. When should I close it? No. When the app is closed, it automatically releases the file reference. However, will there be an exception in "close () was never explicitly called on database? If you note that when the connection is hung there, you do not get the exception. You only encounter exceptions when the connection has been established and you try to open another one. Therefore, you only need to open the connection once. Use this method as follows: public class DatabaseHelper extends OrmLiteSqliteOpenHelper {private static DatabaseHelper instance; public static synchronized DatabaseHelper getHelper (Context context) {if (instance = null) instance = new DatabaseHelper (context); return instance;} // Other stuff ...} that's all...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.