Android--sqlite implementing Object-oriented Crud

Source: Internet
Author: User

Now a bit anxious, don't want to write code, so write a blog to relax.

Just learned the use of SQLite in Android, in fact, it is not difficult, but with the JDBC operation database, this is still a bit uncomfortable, and I haven't written the bottom of the package, using the SSM framework these do not need to consider ... Okay, no more nonsense, just set up a test project below to try the application of SQLite in Android.


1. Create a new project




2. Configuring the JUnit test environment

Open the Androidmanifest.xml file for JUnit-related configuration, as follows:



3. Source code

There are a lot of articles on how to use SQLite in Android, and I also refer to those articles for learning. As a developer of the Java EE direction, I am accustomed to object-oriented programming, and Lao Luo's video and some other tutorials about crud operations using strings, which I am a bit uncomfortable, all of me in the process of learning to change to object-oriented crud operations, so it is easy to use. Principle, API What I will not say, Baidu came out of the swish, the following direct code (complete project download, point here):

Such a class that inherits Sqliteopenhelper mainly has a few functions:

A. Creating databases and tables

B. If the database has different versions then the database will be updated

C. Call the object of this class to obtain read and write access to the database


Package Com.example.db;import Android.content.context;import Android.database.sqlite.sqlitedatabase;import Android.database.sqlite.sqliteopenhelper;public class DBHelper extends Sqliteopenhelper {private static final String database_name = "Test.db";p rivate static final int database_version = 1;public DBHelper (context context) {//Cursorfactory Set to NULL, using the default value super (context, database_name, NULL, database_version);}  The first time the database is created onCreate is called @overridepublic void OnCreate (Sqlitedatabase db) {String sql = "Create TABLE IF not EXISTS person "+" (ID INTEGER PRIMARY KEY autoincrement,name varchar (+), sex VARCHAR (8)) ";d b.execsql (SQL);} If the database_version value is changed to 2, the system discovers that the existing database version is different, calling Onupgrade@overridepublic void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {db.execsql ("ALTER TABLE base_info ADD COLUMN other STRING");}}

You can see that a database called test.db is created with a table person with three fields in it: Primary key-id, name-name, gender-sex.


The following entity classes are generated for this table:

Package Com.example.pojo;public class Person {private int id;private string name;private string sex;public int getId () {RE Turn ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String Getsex () {return sex;} public void Setsex (String sex) {this.sex = sex;} @Overridepublic String toString () {return "person [id=" + ID + ", name=" + name + ", sex=" + Sex + "]";}}

To implement CRUD operations, we create an interface that defines the Crud method:

Package Com.example.dao;import Com.example.pojo.person;public Interface Ipersondao {public boolean insert (person Person);p Ublic boolean delete (int id);p the ublic boolean update (person person);p the ublic person select (int id);}

To implement the Ipersondao interface, define a specific business method:

Package Com.example.dao.impl;import Android.content.context;import Android.database.cursor;import Android.database.sqlite.sqlitedatabase;import Com.example.dao.ipersondao;import Com.example.db.DBHelper;import Com.example.pojo.person;public class Persondaoimpl implements Ipersondao {DBHelper helper = Null;public Persondaoimpl ( Context context) {helper = new DBHelper (context);} @Overridepublic Boolean insert (person person) {Boolean flag = false; Sqlitedatabase Database = null;try {String sql = "INSERT into person (name,sex) VALUES (?,?)"; Database = Helper.getwritabledatabase ();d atabase.execsql (SQL, New Object[]{person.getname (), Person.getsex ()}), Flag = true;} catch (Exception e) {e.printstacktrace ();} Finally{if (database!=null) {database.close ();}} return flag;} @Overridepublic Boolean Delete (int id) {Boolean flag = false; Sqlitedatabase Database = null;try {String sql = "DELETE from person WHERE id=?"; Database = Helper.getwritabledatabase ();d atabase.execsql (SQL, new object[]{integer.tostring (ID)}); flag = true;} catch (Exception e) {e.printstacktrace ();} Finally{if (database!=null) {database.close ();}} return flag;} @Overridepublic boolean update (person person) {Boolean flag = false; Sqlitedatabase Database = null;try {String sql = "UPDATE person set name=?", sex=? where id=? "; Database = Helper.getwritabledatabase ();d atabase.execsql (SQL, New Object[]{person.getname (), Person.getsex (), Person.getid ()}); flag = true;} catch (Exception e) {e.printstacktrace ();} Finally{if (database!=null) {database.close ();}} return flag;} @Overridepublic person Select (int id) {Person person = new person (); Sqlitedatabase Database = null;try {String sql = "SELECT * from person where id=?"; Database = Helper.getreadabledatabase (); cursor cursor = database.rawquery (sql, new string[]{integer.tostring (ID)}); while (Cursor.movetonext ()) {int _id = Cursor.getint (Cursor.getcolumnindex ("id")); String _name = cursor.getstring (Cursor.getcolumnindex ("name")); String _sex = cursor.getstring (Cursor.getcolumnindex ("Sex"));p Erson.setId (_id);p erson.setname (_name);p erson.setsex (_sex);}} catch (Exception e) {e.printstacktrace ();} Finally{if (database!=null) {database.close ();}} return person;}}

After the completion of the unit test can begin, green ...

Package Com.example.test;import Com.example.dao.ipersondao;import Com.example.dao.impl.persondaoimpl;import Com.example.pojo.person;import Android.test.androidtestcase;import android.util.log;public class Test extends androidtestcase {public void Insertdb () {Ipersondao Persondao = new Persondaoimpl (GetContext ()); Person man = new Person ();p erson.setname ("John Doe");p erson.setsex ("male");p Ersondao.insert (person);} public void Selectdb () {Ipersondao Persondao = new Persondaoimpl (GetContext ()); Person person = persondao.select (1); LOG.I ("Info", person.tostring ());} public void UpdateDB () {Ipersondao Persondao = new Persondaoimpl (GetContext ()); Person person = persondao.select (1);p erson.setname ("Change name");p Erson.setsex ("Unknown");p ersondao.update (person);} public void Deletedb () {Ipersondao Persondao = new Persondaoimpl (GetContext ());p Ersondao.delete (2);}}


Export the Test.db file and open it in SQLite expert:



This is the success of the Insert test example, the other will not put the map, the software Baidu can be downloaded.



(Reproduced Annotated Source: Http://blog.csdn.net/zhshulin)

Android--sqlite implementing Object-oriented Crud

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.