SQLite database for four ways to store Android data

Source: Internet
Author: User

Test.java:

/** * This example solves the problem: * Core issue: Create a Database object through the Sqliteopenhelper class * operation of database objects through database object * 1.SQL statement Operation SQLite Database * 2. Google provides API to SQLite database operation * 3. SQLite operations on Transactions */import Com.ghsy.createsqlitedb.db.myopenhelper;import Android.content.contentvalues;import Android.database.cursor;import Android.database.sqlite.sqlitedatabase;import Android.test.AndroidTestCase;public Class Test extends Androidtestcase {myopenhelper oh; Sqlitedatabase db;public void Test () {//Create a Myopenhelper object//Modify the version number here, the upgrade method is executed--upgrade method adds a column Myopenhelper Oh = New Myopenhelper (GetContext (), "people.db", NULL, 3);//If the database does not exist, first create the database, then open the database, if it already exists, directly open sqlitedatabase db = Oh.getwritabledatabase ();d b.close ();} Test framework Initialization Complete/** * This method was called before a test is executed */@Overrideprotected void SetUp () throws Exception {//T ODO auto-generated Method Stubsuper.setup (); oh = new Myopenhelper (GetContext (), "people.db", NULL, 3);d B = oh.getwritable Database ();} ===========sql Statement mode operation SQLite database ================================public void Insert () {DB.execsql ("INSERT into person (name, phone, money) VALUES (?,?,?)", new object[] {"Daming", "18666", 6000});d B.execsql ("Inser T into person (name, phone, money) VALUES (?,?,?) ", new object[] {" Small red "," 18666 ", 6000});d B.execsql (" INSERT into person (NA Me, phone, money) VALUES (?,?,?) ", new object[] {" Scarlet "," 18666 ", 6000});} public void Delete () {db.execsql ("delete from person where name =?", new object[] {"Daming"}); public void Update () {db.execsql ("update person Set money = 10000 WHERE name =?", new object[] {"Xiaoming"}); public void query () {///cursor, which holds the data returned by the query, gets the same method as the resultset height cursor c = db.rawquery ("SELECT * from person", new string[] {}); whi Le (C.movetonext ()) {String name = c.getstring (C.getcolumnindex ("name")); String phone = c.getstring (C.getcolumnindex ("Phone")); SYSTEM.OUT.PRINTLN (name + ";" + Phone);}} ============== Google provides API to SQLite database operation ======================/** * Api-insert data to table */public void Insertapi () { Contentvalues CV = new Contentvalues () cv.put ("Name", "Twilight"); Cv.put ("Phone"), 15666); Cv.put ("Money", 630); Long id = db.insert ("person", NULL, CV); SYSTEM.OUT.PRINTLN (ID);} /** * api-delete data from Table * * @return The number of rows affected */public int Deleteapi () {int affectednum = DB.D Elete ("Person", "name=", new string[] {"Little Red"}); return affectednum;} /** * api-update */public void Updateapi () {contentvalues contentvalues = new Contentvalues (); Contentvalues.put ("Name", " Contentvalues.put ("Money", "ten");//return the number of rows affecteddb.update ("person", contentvalues, "Name=?", New string[] {"Scarlet"});} public void Queryapi () {CURSOR cursor = db.query (' person ', new string[] {"Phone", "money"},null, NULL, NULL, NULL, NULL) ; while (Cursor.movetonext ()) {String phone = cursor.getstring (Cursor.getcolumnindex ("Phone")); String money = cursor.getstring (Cursor.getcolumnindex ("money")); SYSTEM.OUT.PRINTLN (Phone + "# #" + Money);}}   ===============sqlite operation of the transaction =====================/** * Bank transfer operation */public Void Transation () {db.begintransaction (); try {//name for Twilight users to the small red transfer contentvalues contentvalues=new contentvalues ();   Contentvalues.put ("Money", 1000);   Db.update ("Person", contentvalues, "Name=", New string[]{"Twilight"});   Contentvalues contentvalues2=new contentvalues ();   Contentvalues2.put ("Money", 1100);   Db.update ("Person", ContentValues2, "Name=", New string[]{"Little Red"});   All statements are executed, and if there is no exception, the token db.settransactionsuccessful () that sets the transaction success is executed. Finally {//checks the identity of the transaction and, if the Settransactionsuccessful () method setting flag is not called, rolls back the transaction.       Otherwise commits the transaction.   Db.endtransaction (); }}}

Myopenhelper.java

**sqliteopenhelper: * A helper class to manage database creation and version management. * Therefore, Sqliteopenhelper is the operation of the library itself. To manipulate data in a library, you need to use the method of the library object. */import Android.content.context;import Android.database.sqlite.sqlitedatabase;import Android.database.sqlite.sqlitedatabase.cursorfactory;import Android.database.sqlite.sqliteopenhelper;public Class Myopenhelper extends Sqliteopenhelper {//name: Database file name//factory: Cursor Factory//version: version, must be greater than or equal to 1public myopenhelper ( Context context, String name, Cursorfactory factory, int version) {Super (context, name, Factory, version);//TODO Auto-gen Erated Constructor stub}//Database is created when you call @overridepublic void OnCreate (Sqlitedatabase db) {//Create a person table Db.execsql ("Create Table person (_id Integer primary key autoincrement, name Char (TEN), Phone char (20)) "); System.out.println ("OnCreate called");} Database upgrade calls @overridepublic void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {//TODO auto-generated Metho D stubSystem.out.println ("Onupgrade called");d B.execsql ("ALTER TABLE person Add Money char (20) ");}} 



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.