How to learn and use SQLite in Android

Source: Internet
Author: User
Tags call back

SQLite Introduction

SQLite is a lightweight, embedded, and relational database. It is currently used in iPhone, Android, and other mobile phone systems. SQLite is portable, easy to use, small, efficient, and reliable. SQLite is embedded into applications that use it.ProgramThey share the same process space, rather than a separate process. From the external perspective, it is not like an RDBMS, but inside the process, it is complete, self-contained database engine.

In Android, when you need to operate the SQLite database, you need to get a sqliteopenhelper object, while sqliteopenhelper is an abstract class. You need to inherit this class and implement some methods in this class.

1. inherit from sqliteopenhelper and you will have the following two methods:

◆ Getreadabledatabase () Create or open a query database

◆ Getwritabledatabase () Create or open a writable Database

◆ They will return the sqlitedatabase object, and the user will perform subsequent operations through the obtained sqlitedatabase object

2. At the same time, the user can override the following callback functions and call back the following methods when operating the database:

◆ Oncreate (sqlitedatabase): This method is called when the database is created for the first time. Generally, we create a database table in this method.

◆ Onupgrade (sqlitedatabase, Int, INT): When the database needs to be modified, the android system will actively call this method. In general, we delete database tables and create new database tables in this method. Of course, whether other operations are required depends on the needs of the application.

◆ Onopen (sqlitedatabase): This is the callback function when the database is opened and is generally not used.

Note:

1. The following constructor must exist in the subclass of sqliteoepnhelper:

    1. Public databasehelper (context, string name, cursorfactory factory,
    2. Int version ){
    3. // The constructor in the parent class must be called through Super
    4. Super (context, name, factory, version );
    5. }
    6.  

For convenience, you can also create other constructors with two or three parameters.

2. The public void oncreate (sqlitedatabase dB) function is executed when getreadabledatabase () is called or getwritabledatabase () is called to create a database for the first time. In fact, it is the first time that the sqlitedatabse object is obtained, to call this method.

    1. Public void oncreate (sqlitedatabase dB ){
    2. System. Out. println ("Create a database ");
    3. // Execsql function is used to execute SQL statements
    4. Db.exe csql ("create table user (ID int, name varchar (20 ))");
    5. }
    6.  

When inserting a record into a database table, you must first include the data in a contentvalues and insert a key-value pair to the object. The key-value pair is the column name, the value is the value that you want to insert into this column. The value must be consistent with the data type in the database. Call the getwritabledatabase method of databasehelper to obtain the databasehelper object that can be written, and then insert records into it. Pay attention to the transmission of parameters that call the insert, update, or query method of the databasehelper object.

In addition, after the query method is executed, a cursor is returned. The cursor first points to the previous row of the first row in the record set. Therefore, you must first call cursor. next () move the cursor to the first row of the record set, and then obtain the data.

JavaCode

  1. Public class sqliteactivity extends activity {
  2. /** Called when the activity is first created .*/
  3. Private button createbutton;
  4. Private button insertbutton;
  5. Private button updatebutton;
  6. Private button updaterecordbutton;
  7. Private button querybutton;
  8. @ Override
  9. Public void oncreate (bundle savedinstancestate ){
  10. Super. oncreate (savedinstancestate );
  11. Setcontentview (R. layout. Main );
  12. Createbutton = (button) findviewbyid (R. Id. createdatabase );
  13. Updatebutton = (button) findviewbyid (R. Id. updatedatabase );
  14. Insertbutton = (button) findviewbyid (R. Id. insert );
  15. Updaterecordbutton = (button) findviewbyid (R. Id. Update );
  16. Querybutton = (button) findviewbyid (R. Id. query );
  17. Createbutton. setonclicklistener (New createlistener ());
  18. Updatebutton. setonclicklistener (New updatelistener ());
  19. Insertbutton. setonclicklistener (New insertlistener ());
  20. Updaterecordbutton. setonclicklistener (New updaterecordlistener ());
  21. Querybutton. setonclicklistener (New querylistener ());
  22. }
  23. Class createlistener implements onclicklistener {
  24. @ Override
  25. Public void onclick (view v ){
  26. // Create a databasehelper object
  27. Databasehelper dbhelper = new databasehelper (sqliteactivity. This, "test_mars_db ");
  28. // A database is created or opened only after the getreadabledatabase () method of the databasehelper object is called or the getwritabledatabase () method.
  29. Sqlitedatabase DB = dbhelper. getreadabledatabase ();
  30. }
  31. }
  32. Class updatelistener implements onclicklistener {
  33. @ Override
  34. Public void onclick (view v ){
  35. Databasehelper dbhelper = new databasehelper (sqliteactivity. This, "test_mars_db", 2 );
  36. Sqlitedatabase DB = dbhelper. getreadabledatabase ();
  37. }
  38. }
  39. Class insertlistener implements onclicklistener {
  40. @ Override
  41. Public void onclick (view v ){
  42. // Generate the contentvalues object
  43. Contentvalues values = new contentvalues ();
  44. // To insert a key-value pair to the object, the key-value pair is the column name and the value is the value to be inserted into the column. The value must be consistent with the data type in the database.
  45. Values. Put ("ID", 1 );
  46. Values. Put ("name", "zhangsan ");
  47. Databasehelper dbhelper = new databasehelper (sqliteactivity. This, "test_mars_db", 2 );
  48. Sqlitedatabase DB = dbhelper. getwritabledatabase ();
  49. // Call the insert method to insert data to the database.
  50. DB. insert ("user", null, values );
  51. }
  52. }
  53. // The update operation is equivalent to executing the update statement in the SQL statement.
  54. // Update table_name setXxcol=XxxWhereXxXxcol= XX...
  55. Class updaterecordlistener implements onclicklistener {
  56. @ Override
  57. Public void onclick (view arg0 ){
  58. // Todo auto-generated method stub
  59. // Get a writable sqlitedatabase object
  60. Databasehelper dbhelper = new databasehelper (sqliteactivity. This, "test_mars_db ");
  61. Sqlitedatabase DB = dbhelper. getwritabledatabase ();
  62. Contentvalues values = new contentvalues ();
  63. Values. Put ("name", "zhangsanfeng ");
  64. // The first parameter is the name of the table to be updated.
  65. // The second parameter is a contentvaleus object.
  66. // The third parameter is the WHERE clause.
  67. DB. Update ("user", values ,"ID=? ", New string [] {" 1 "});
  68. }
  69. }
  70. Class querylistener implements onclicklistener {
  71. @ Override
  72. Public void onclick (view v ){
  73. System. Out. println ("AAA ------------------");
  74. Log. D ("mydebug", "myfirstdebugmsg ");
  75. Databasehelper dbhelper = new databasehelper (sqliteactivity. This, "test_mars_db ");
  76. Sqlitedatabase DB = dbhelper. getreadabledatabase ();
  77. Cursor cursor = dB. Query ("user", new string [] {"ID", "name "},"ID=? ", New string [] {" 1 "}, null );
  78. While (cursor. movetonext ()){
  79. String name = cursor. getstring (cursor. getcolumnindex ("name "));
  80. System. Out. println ("query --->"+ Name );
  81. }
  82. }
  83. }
  84. }
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.