Android database learning 123

Source: Internet
Author: User

Android database learning 123

I personally feel that not many Android databases are used. After all, many applications now interact directly with the server database or directly obtain interface data through APIS, however, it is undeniable that the built-in database still has some functions, so we still need to study and study the built-in database. (Above all nonsense) enter the subject:

1. Create a database

 

Android provides a SQLiteOpenHelper help class for better database management. With this class, you can easily create and upgrade databases. SQLiteOpenHelper is an abstract class. What is an abstract class? Abstract classes are like leaders. Generally, they do not work (instantiate) themselves, but only send code to the commander. To use this class, you must create a class to inherit it. In addition, there are two abstract methods in this class: onCreate () and onUpgrade (). We must rewrite these two methods in our help class, then use these two methods to create and upgrade the database.

This class also contains two important instance methods: getReadableDatabase () and getWritableDatabase (). The two methods can both create or open an existing database (open if the database exists, and create a new database if it does not exist). What are the differences between the two methods? When the database cannot be written (for example, the disk is full), the first method is read-only, and the second method is abnormal.

I will not talk much about the nonsense theory. Let's look at the table creation statement below:

create table Book(id integer primary key autoincrement,author text,price real,pages integer, name text)


If you cannot understand the preceding SQL statements, it is not difficult.

Write the following code:

Package org. lxh. demo; import android. content. context; import android. database. sqlite. SQLiteDatabase; import android. database. sqlite. SQLiteDatabase. cursorFactory; import android. database. sqlite. SQLiteOpenHelper; import android. widget. toast; public class MyDatabaseHelper extends SQLiteOpenHelper {public static final String CREATE_BOOK = "create table Book (" + "id integer primary key autoincrement," + "author text," + "price real, "+" pages integer, "+" name text) "; // private Context mcontext; // Context object, the public MyDatabaseHelper (Context context, String name, // constructor automatically generates CursorFactory factory, int version) {super (context, name, factory, version); mcontext = context ;}@ Overridepublic void onCreate (SQLiteDatabase db) {// db.exe cSQL (CREATE_BOOK) is automatically overwritten; // create a database Toast. makeText (mcontext, "Create succeeded", Toast. LENGTH_SHORT ). show () ;}@ Overridepublic void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {// Auto override // TODO Auto-generated method stub }}


Then we create a button in the layout file:

 
     
  
   
  
 


Finally, create a button to listen in MainActivity.

Package org. lxh. demo; import android. app. activity; import android. OS. bundle; import android. view. view; import android. view. view. onClickListener; import android. widget. button; public class MainActivity extends Activity {private Button create; private MyDatabaseHelper myDatabaseHelper; public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); // life cycle method super. setContentView (R. layout. main); // set the layout manager to use create = (Button) findViewById (R. id. btn); myDatabaseHelper = new MyDatabaseHelper (this, "BookStore", null, 1); // There are four parameters in the constructor. Complete create. setOnClickListener (new OnClickListener () {// anonymous internal class public void onClick (View v) {myDatabaseHelper. getWritableDatabase (); // call the instance method getWritableDatabase () to create a database }});}}


Click the create button to create the database. If you do not click the create button, you can test the Toast (because it only appears once, that is, the database is only created once ):

2. update the database:

It is useless to create an override method in MyDatabaseHelper, that is, onUpgrade () is used to update the database. For example, if the database already has a Book table, we want to create a Catagory table:

Package org. lxh. demo; import android. content. context; import android. database. sqlite. SQLiteDatabase; import android. database. sqlite. SQLiteDatabase. cursorFactory; import android. database. sqlite. SQLiteOpenHelper; import android. util. log; import android. widget. toast; public class MyDatabaseHelper extends SQLiteOpenHelper {public static final String CREATE_BOOK = "create table Book (" + "id integer primary key autoincrement," + "author text," + "price real, "+" pages integer, "+" name text )"; // write the SQL statement public static final String CREATE_CATEGORY = "create table Category (" // create an external table + "id integer primary key autoincrement," + "category_name text, "+" category_code integer) "; private Context mcontext; // Context object. In many cases, public MyDatabaseHelper (context Context, String name, // The constructor also automatically generates CursorFactory factory, int version) {super (context, name, factory, version); mcontext = context ;}@ Overridepublic void onCreate (SQLiteDatabase db) {// db.execsql(create_book‑mongodb.exe cSQL (CREATE_CATEGORY); Toast. makeText (mcontext, "Create succeeded", Toast. LENGTH_SHORT ). show () ;}@ Overridepublic void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {// automatically override db.exe cSQL ("drop table if exists Book "); // remove db.exe cSQL ("drop table if exists Category"); onCreate (db); // create a database later }}


MainActivity. java:

Package org. lxh. demo; import android. app. activity; import android. OS. bundle; import android. util. log; import android. view. view; import android. view. view. onClickListener; import android. widget. button; public class MainActivity extends Activity {private Button create; private MyDatabaseHelper myDatabaseHelper; public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); // life cycle method super. setContentView (R. layout. main); // set the layout manager to use create = (Button) findViewById (R. id. btn); myDatabaseHelper = new MyDatabaseHelper (this, "BookStore", null, 2); // In this example, the version is changed to 2create. setOnClickListener (new OnClickListener () {// anonymous internal class public void onClick (View v) {myDatabaseHelper. getWritableDatabase (); // call the instance method getWritableDatabase () to create a database Log. d ("Success", "chenggong ");}});}}


Run the following command:

How can we know that the database we created is successful? Where can we see them? We are going to use adb. This is a debugging tool that comes with the Android SDK. How can we use it? First, configure your platform_tools directory to the environment variable:

Enter adb shell on the DOS interface to go to the device console:

Then type cd/data/org. lxh. demo/databases:

Type sqlite3 BookStore. db:

Then type:. table:

 

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.