Create a SQLite database under Android

Source: Internet
Author: User

Database: SQLite (lightweight, embedded database)

A large number of similar structures of data storage, fast query. Special files (generated in a certain format)

Creation of a database

Create a file

1. Declare the file object, the file will not be created.

File File = new ("filename");

2. Write files (files will be created)

FileOutputStream fos = new FileOutputStream (file);

Fos.write ("Hdahfdsaklfh". GetBytes ());

Create a database

1. Implementation of Sqliteopenhelper subclass Personsqliteopenhelper

 Public classPersonsqliteopenhelperextendsSqliteopenhelper { PublicPersonsqliteopenhelper (Context context, String name, Cursorfactory factory,intversion) {        Super(context, name, Factory, version); //TODO auto-generated Constructor stub} @Override Public voidonCreate (sqlitedatabase arg0) {//TODO auto-generated Method Stub} @Override Public voidOnupgrade (Sqlitedatabase db,intOldversion,intnewversion) {        //TODO auto-generated Method Stub    }}

Several parameters of the Sqliteopenhelper are explained as follows:

Android.database.sqlite.SQLiteOpenHelper.SQLiteOpenHelper (context context, String name, Cursorfactory factory,intversion) Create a helper object to create, open, and/or manage a database. This method is always returns very quickly. The database is not actually created or opened until one of the getwritabledatabase or getreadabledatabase are called. Parameters:context to open or create the databasename of the database file, orNULL  forAn in-memory Databasefactory to use forCreating cursor objects, orNULL  forThedefaultVersion number of the database (starting at1);ifThe database is older, onupgrade'll be used to upgrade the database;ifThe database is newer, Ondowngrade'll be used to downgrade the database

2.getwritabledatabase/getreadabledatabase ()

New Testpersondb.java

 package   Com.wuyudong.db.test;  import   Com.wuyudong.db.PersonSQLiteOpenHelper;  import   Android.test.AndroidTestCase;  public  class  TESTPERSONDB extends   Androidtestcase { Span style= "color: #0000ff;" >public  void  testcreatedb () throws   Exception {Personsqliteopenhelper helper  = new   Personsqliteopenhelper (GetContext ());    Helper.getwritabledatabase (); }}

3.oncreate () database The first time the execution method is created, which is appropriate for initializing the database table structure

 //  Called when the database was created for the    First time.  //  The method that executes when the database is first created  //  If the database is already created, it will not be executed again.  //  for initialization of database table structure  //  DB represents the current database   @Override  Span style= "color: #0000ff;" >public  void   OnCreate (Sqlitedatabase db { //  Initialize the table structure of the database  DB.EXECSQ L ("CREATE TABLE person" (ID integer primary key autoincrement, name varchar (), number varchar) "); }

Attention:

The SQLite database is an embedded lightweight database that does not differentiate between data types, and does not validate the length of the data.

New Androidtest Project Test

Copy the following related code in Androidmanifest.xml into the androidmanifest.xml of this project

<?XML version= "1.0" encoding= "Utf-8"?><Manifestxmlns:android= "Http://schemas.android.com/apk/res/android" Package= "Com.wuyudong.db.test"Android:versioncode= "1"Android:versionname= "1.0" >    <USES-SDKandroid:minsdkversion= "8" />    <instrumentation  android:name= " Android.test.InstrumentationTestRunner "  android:targetpackage=" Com.wuyudong.db " />     <ApplicationAndroid:icon= "@drawable/ic_launcher"Android:label= "@string/app_name" >      <uses-library  android:name= "Android.test.runner" />        </Application></Manifest>

The following code is copied:

<?XML version= "1.0" encoding= "Utf-8"?><Manifestxmlns:android= "Http://schemas.android.com/apk/res/android" Package= "Com.wuyudong.db"Android:versioncode= "1"Android:versionname= "1.0" >  <instrumentation  android:name= "Android.test.InstrumentationTestRunner"  android:targetpackage= "com.wuyudong.db" />        <USES-SDKandroid:minsdkversion= "8"android:targetsdkversion= "+" />    <ApplicationAndroid:allowbackup= "true"Android:icon= "@drawable/ic_launcher"Android:label= "@string/app_name"Android:theme= "@style/apptheme" >         <uses-library  android:name= "Android.test.runner" />         <ActivityAndroid:name= "Com.wuyudong.db.MainActivity"Android:label= "@string/app_name" >            <Intent-filter>                <ActionAndroid:name= "Android.intent.action.MAIN" />                <categoryAndroid:name= "Android.intent.category.LAUNCHER" />            </Intent-filter>        </Activity>    </Application></Manifest>

The project structure is as follows:

Personsqliteopenhelper.java complete code is as follows:

 Packagecom.wuyudong.db;ImportAndroid.content.Context;Importandroid.database.sqlite.SQLiteDatabase;ImportAndroid.database.sqlite.SQLiteOpenHelper; Public classPersonsqliteopenhelperextendsSqliteopenhelper {/*** Defines a database-created helper class with two methods that need to be implemented equivalent to the file class * *@authorAdministrator **/     PublicPersonsqliteopenhelper (Context context) {//Context Contexts//person.db Database file name//Factory Wiper Factory//version Database has a revision number starting from 1        Super(Context, "person.db",NULL, 1); //TODO auto-generated Constructor stub    }    //Called when the database was created for the first time . //methods that are executed when the database is first created//If the database has been created, it will not be executed again. //suitable for initialization of database table structure//the DB represents the current database .@Override Public voidonCreate (Sqlitedatabase db) {//Initialize the table structure of the databaseDb.execsql ("CREATE TABLE person" (ID integer primary key autoincrement, name varchar (), number varchar (20)) "); }    //called when the version number of the database has been upgraded. //databases can only be upgraded and cannot be degraded. @Override Public voidOnupgrade (Sqlitedatabase db,intOldversion,intnewversion) {        //TODO auto-generated Method Stub    }}

Run the program

Open person.db

Create a SQLite database under Android

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.