Detailed Android Lightweight Database sqlite_android

Source: Internet
Author: User
Tags sqlite sqlite database

The database is the core of the Android storage solution, SQLite very lightweight in Andorid, and executes SQL statements even faster than MySQL.
Sqlitedatabase is one of the core classes of operating databases in Android, using Sqlitedatabase to open a database or operate on a database, but for database upgrades and easy access, We often use sqliteopenhelper subclasses to complete the creation and open the database operation.
Sqliteopenhelper is an abstract class that has the following two methods that must be implemented:

public void OnCreate (Sqlitedatabase db);//The function calls the public
void Onupgrade (sqlitedatabase db,int oldversion when the database is first created) , int newversion);//Database Update upgrade operation

We create a new class DBHelper extends Sqliteopenhelper

Import Java.util.Random; Import Android.
R.bool;
Import Android.content.Context;
Import Android.database.Cursor;
Import Android.database.sqlite.SQLiteDatabase;
Import Android.database.sqlite.SQLiteDatabase.CursorFactory;

Import Android.database.sqlite.SQLiteOpenHelper;
 public class DBHelper extends Sqliteopenhelper {//Set the default version of the database private static final int verson = 1;

 Custom database name, you can arbitrarily take the name private static final String dbname = "MyDB"; The class that inherits the Sqliteopenhelper class must have its own constructor//constructor 4 parameters that directly call the constructor of the parent class. The first parameter is the class itself; the second parameter is the name of the database; public DBHelper (context context, String name, Cursorfactory factory, int version) {Super
 (context, name, Factory, version); The constructor has 3 parameters, because it fixed the 3rd argument of the above function to null. Public DBHelper (context, String name, int verson) {This [context, name
 , NULL, Verson);
 }//The constructor has only 2 parameters, and the version number is fixed on the basis of the above function as public dbhelper (context, name, Verson); }//The constructor has only 1 parameters, fixed the default database, where we implement additions and deletions for convenience, use it for public dbhelper {This (context, dbname, NULL, Verson);
  The function calls the public void OnCreate (Sqlitedatabase db) {System.out.println ("Create a SQLite database") when it is first established;
      Build Table Statement Note: The data binding String sql = "CREATE table [Test]" ("+" [_id] autoinc, "+" [cursor], because the recordset returned by the object must contain a "_id" field when the data is bound).
  "[Name] varchar," + "[age] varchar," + "PRIMARY KEY ([_id])";

  Db.execsql (SQL);
   Inserts 10 data into the test table for (int i = 1; I <= i++) {String name = ' Jepson ';
   Name+=i;
   String age = ' age ';
   Age+=i;
  Db.execsql ("INSERT into Test (name,age) VALUES (?,?)", New Object[]{name,age}); }//Database update operations public void Onupgrade (sqlitedatabase arg0, int arg1, int arg2) {System.out.println ("update a SQLite
 Database "); ///Custom Query method, which executes the query statement, returns the Cursor object public Cursor query (String sql,string[] args) {//calls the Getreadabledatabase method, if the database file
  Does not exist, the OnCreate method is invoked sqlitedatabase db = This.getreadabledatabase ();
  Cursor Cursor = db.rawquery (sql, args);
 return cursor;
 }
}

In this way, our DBHelper class is written so we can implement a query operation.

first step , Activity_main.xml add ListView Display Control

Activity_main.xml

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"
 xmlns:tools= "http:// Schemas.android.com/tools "
 android:layout_width=" match_parent "
 android:layout_height=" Match_parent "
 android:background= "#FFFFFF"
 android:orientation= "vertical"
 tools:context= ". Mainactivity ">

 <listview
  android:id=" @android: Id/list "
  android:layout_width=" Fill_parent "
  android:layout_height= "wrap_content"
  android:layout_weight= "1"
  android:divider= "#6b6f74"
  android:dividerheight= "1px" >
 </ListView>

</LinearLayout>

The second step is to create a new XML layout file that is used as a layout resource for list items

User_list_cell.xml

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
 android:layout_width=" match_parent "
 android:layout_height=" match_parent "
 android:o" rientation= "vertical" 
 android:background= "#FFFFFF" >
 <!--large font TextView to display name-->
 < TextView
  android:id= "@+id/tvname"
  android:layout_width= fill_parent "android:layout_height=" Wrap_
  Content "
  android:text=" Large "
  android:textcolor=" "#000000"
  android:textsize= "20DP"/>

 <!--small font TextView to show age-->
 <textview
  android:id= "@+id/tvage" android:layout_width= "
  Fill_parent "
  android:layout_height=" wrap_content "
  android:text=" Small "
  android:textcolor=" # 000000 "
  android:textsize=" 14DP "/>

</LinearLayout>

The third step, the main activity

Import Android.os.Bundle;
Import android.app.Activity;
Import android.app.ListActivity;
Import Android.database.Cursor;
Import Android.support.v4.widget.SimpleCursorAdapter;
Import Android.view.Menu;

Import Android.widget.Toast; public class Mainactivity extends listactivity {protected void OnCreate (Bundle savedinstancestate) {super.oncreate (s
  Avedinstancestate);
  Setcontentview (R.layout.activity_main);
 Initview ();
  public void Initview () {//Call constructor with only 1 arguments, instantiate dbhelper dbhelper dbhelper = new DBHelper (this);
  Creates a new Cursor object to hold the results returned by the query method, querying all records in the test table Cursor Cursor = Dbhelper.query ("SELECT * from Test", null); Create Simplecursoradapter object, 5 parameters,//First is context, write current this on line//The second is the layout file, I am here a custom layout file User_list_cell.xml// The third is the cursor object//The fourth corresponds to, cursor query, need to display the field name, such as I want to display name and age//fifth is the corresponding list item layout in the control ID simplecursoradapter Simplecursoradapter = new Simplecursoradapter (this, R.layout.user_list_cell, cursor, new string[) {"Name", "Age" }, new int[] {r.id.Tvname, r.id.tvage});
  Setlistadapter (Simplecursoradapter);
 Toast.maketext (This, "Query success", Toast.length_short). Show ();
 }
}

Perform a look, we are not the query succeeded?

Operation SQLite database should understand that there are two ways to modify the database, one is the previous use of the Rawquery method to execute the SQL statement directly, the other is to use the Sqlitedatabase class of the corresponding methods to operate, below a second example, Like we're inserting data name=11 age=22

Import Android.os.Bundle;
Import android.app.Activity;
Import android.app.ListActivity;
Import Android.database.Cursor;
Import Android.support.v4.widget.SimpleCursorAdapter;
Import Android.view.Menu;

Import Android.widget.Toast; public class Mainactivity extends listactivity {protected void OnCreate (Bundle savedinstancestate) {super.oncreate (s
  Avedinstancestate);
  Setcontentview (R.layout.activity_main);
 Initview ();
  public void Initview () {//Perform add operation dbhelper dbhelper = new DBHelper (this);
  Get Write permission getwritabledatabase sqlitedatabase db = Dbhelper.getwritabledatabase ();
  New contentvalues Save Insert data contentvalues CV = new Contentvalues ();
  Cv.put ("name", "11");
  Cv.put ("Age", "22");
  Db.insert ("Test", NULL, CV);

  Toast.maketext (This, add success, Toast.length_short). Show ();
  The query operation////the constructor with only 1 arguments, instantiating dbhelper//dbhelper dbhelper = new DBHelper (this); Creates a new Cursor object to hold the results returned by the query method, querying all records in the test table//cursor Cursor = Dbhelper.query ("SELECT * from Test", null); Create a Simplecursoradapter object, 5 parameters,////the first is the context, write the current this on the line////the second is the layout file, I am here to customize the layout file User_list_cell.xml//// The third is the cursor object////Fourth is, cursor query, you need to display the field name, such as I want to display name and age////fifth is the corresponding list item layout of the control ID//simplecursoradapter Simplecursoradapter = new Simplecursoradapter (this,//R.layout.user_list_cell, cursor,//new string[] {"Name", "a
  GE "}, new int[] {r.id.tvname,//r.id.tvage});
  Setlistadapter (Simplecursoradapter);
 Toast.maketext (This, "Query success", Toast.length_short). Show (); 
 }
}

After the insert succeeds, insert the statement annotation, remove the comment from the query, reboot, and find the last one more item to add success.

In addition, the cursor object obtained by the query record needs to be movetofirst,movetonext,movtoposition (position) to move the pointer to the corresponding position to read the query result.

Import Android.os.Bundle;
Import android.app.Activity;
Import android.app.ListActivity;
Import Android.database.Cursor;
Import Android.support.v4.widget.SimpleCursorAdapter;
Import Android.view.Menu;

Import Android.widget.Toast; public class Mainactivity extends listactivity {protected void OnCreate (Bundle savedinstancestate) {super.oncreate (s
  Avedinstancestate);
  Setcontentview (R.layout.activity_main);
 Initview ();
  public void Initview () {//Parsing cursor object's query operation DBHelper dbhelper = new DBHelper (this);
  Sqlitedatabase db = Dbhelper.getwritabledatabase ();
  Cursor Cursor = db.query ("Test", NULL, NULL, NULL, NULL, NULL, NULL, NULL);
  Defines the result string, string results = ""; It is important to judge that cursor is not empty if (cursor!= null) {while (Cursor.movetonext ()) {String name = cursor.getstring (cursor.ge Tcolumnindex ("name"))//Gets the value of the name column String age = cursor.getstring (Cursor.getcolumnindex ("Age"));//Get the value of the Age column result
   + = "Name:" + name + ", Age:" + ages + "\ n"; }} cursor.close ();
  Db.close ();
  SYSTEM.OUT.PRINTLN (result);

  Toast.maketext (this, result, Toast.length_short). Show ();
  Perform add action//DBHelper dbhelper = new DBHelper (this);
  Get Write permission Getwritabledatabase//Sqlitedatabase db = Dbhelper.getwritabledatabase ();
  New contentvalues Save Insert Data//contentvalues CV = new Contentvalues ();
  Cv.put ("name", "11");
  Cv.put ("Age", "22");
  Db.insert ("Test", NULL, CV);

  Toast.maketext (This, add success, Toast.length_short). Show ();
  The query operation////the constructor with only 1 arguments, instantiating dbhelper//dbhelper dbhelper = new DBHelper (this);
  Creates a new Cursor object to hold the results returned by the query method, querying all records in the test table//cursor Cursor = Dbhelper.query ("SELECT * from Test", null); Create a Simplecursoradapter object, 5 parameters,////the first is the context, write the current this on the line////the second is the layout file, I am here to customize the layout file User_list_cell.xml//// The third is the cursor object////Fourth is, cursor query, you need to display the field name, such as I want to display name and age////fifth is the corresponding list item layout of the control ID//simplecursoradapter Simplecursoradapter = new Simplecursoradapter (this,//R.layout.user_list_cell, CUrsor,//new string[] {"Name", "Age"}, new int[] {r.id.tvname,//r.id.tvage});
  Setlistadapter (Simplecursoradapter);
 Toast.maketext (This, "Query success", Toast.length_short). Show (); 
 }
}

After execution, you can see that name and age are all captured and displayed in toast and System.out. Isn't it fun?

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.