Sqlitedatabase Database Operation detailed

Source: Internet
Author: User
Tags sqlite

It took a little time today to summarize the knowledge of the data. The database Sqlitedatabase database in Android, which operates more than the ormlite database (third-party) trouble points, But I am familiar with this kind of database operation, so I used this kind of database,If you are wrong, please criticize me.
1.SQLiteDatabasesqlitedatabase itself is a database operation class, but if you want to do the operation of the database, but also need the help of Android.database.sqlite.SQLiteOpenHelper class ,the Execsql () method cannot return a value when executing an SQL statementDescription of the Execsql () method for Android
2.SQLiteOpenHelper(excerpt from Li Xinghua Android Combat Classic)Sqliteopenhelper is an auxiliary class for database operations, and it is an abstract class, so it is necessary to define its subclasses when used, and to replicate the corresponding abstract methods in subclasses.
three callback methods are defined in the Sqliteopenhelper class. 2.1 onCreate () This method invokes the corresponding database table when the database is first used, but this method is not invoked when instantiating an object of the Sqliteopenhelper class, but rather through the object Called when the Getreadabledatabase () or Getwriteabledatabase () method is called. 2.2 Onupgrade ()This method is called when the database is upgraded, and it is generally possible to delete the data table in this method, and the OnCreate () method is often used to recreate the new data table after the table is deleted. 2.3 onopen () This method is called when the database is opened, but generally the user does not need to replicate this method.
3.Android Database Additions and deletions change the sample code3.1 layout diagram as follows
the code for the 3.2 host faces is as follows:
Package Com.example.contentvaluespractice;import Android.app.activity;import Android.content.contentvalues;import Android.database.cursor;import Android.database.sqlite.sqlitedatabase;import Android.database.sqlite.sqliteopenhelper;import Android.os.bundle;import Android.view.view;public Class     Mainactivity extends Activity {private sqlitedatabase db;           @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                      Setcontentview (r.layout. Activity_main); Sqliteopenhelper helper= New Databasehelper (this); The//sqliteopenhelper helper class performs a database operation//execution OnCreate method to return the database.      The DB database creates db=helper.getwritabledatabase () only after the Getwritetabledatabase () or Getreadabledatabase () method is executed OnCreate () method.      }//To insert data into the database in two ways, one is through SQL statements, one is provided via Android method public void Insert (view view) {///Insert Data SQL statement method String sql= "INSERT into Persondata (name,age,birthday) VALUES (' DMK ', null, ' 1988-9-10 ')";//sqlStatement to perform an insert operation Db.execsql (SQL); The second way to insert data is the method provided in Android//using Contentvalues for insert Operation Contentvalues equivalent to a map in Java in the form of a key-value pair contentvalues cv= new Conten       Tvalues ();      Cv.put ("name", "DMJ");      Cv.put ("Age", 26);          Db.insert ("Persondata", NULL,CV); }//delete data from the database two ways, one is through the SQL statement, one is provided through the method of Android public void Delete (view view) {//1. Using the way in Android String wh Ereclause= "Name=?";       Delete condition string[] whereargs={"DMK"};      Db.delete ("Persondata", Whereclause, Whereargs);       2. Use the Execsql method to implement String sql= "delete from persondata where name= ' dmj '";     Db.execsql (SQL);    }//Update data in the database 2 ways public void Update (view view) {//1. Using contentvalues contentvalues cv= new Contentvalues () in Android; Cv.put ("name", "DF"); Add the field and content you want to change//String whereclause= "Name=?";    /string[] whereargs={"DMK"};//db.update ("Persondate", CV, Whereclause, Whereargs);    Db.update ("Persondata", CV, "Name=", New string[]{"DMK"}); 2. Using Execsql to implement String sql= "Update [persondata] set age=20 where name= ' dmj '";   Db.execsql (SQL); The Execsql () method cannot return a value,}//Query data 1/* * The public Cursor query that implements queries via query (string table, string[] columns, string Selec      tion, string[] Selectionargs, String groupBy, String having, string-by-clause, string limit) Each parameter description: Table: Tables Name     Colums: Column name array selection: Conditional clauses, equivalent to where example "Name=?" Selectionargs: An example of a parameter array for a conditional statement new string[]{"DMK"} groupBy: Group having: grouping conditions Order BY: Sorting class limit: Limits for paged Queries Curs Or: The return value, equivalent to the result set resultset */public void query (view view) {Cursor cs= db.query ("Persondata", NULL, NULL, NULL, n        ULL, NULL, NULL);                   if (Cs.movetonext ()) {for (int i=0;i<cs.getcount (); i++) {cs.move (i);                   String name=cs.getstring (Cs.getcolumnindex ("name"));                   int Age=cs.getint (Cs.getcolumnindex ("Age")); System.                   Out.println (name+ ":" +age); System.out.println (Cs.getcolumnindex ("Name")); System.                   Out.println (Cs.getcolumnindex ("Age")); System.              Out.println (Cs.getcolumncount ()); }}}//Data query 2//query by Rawquery/*/Cursor C = Db.rawquery ("SELECT * from user where username   =? ", New stirng[]{" Jack Johnson "});   if (Cursor.movetofirst ()) {String password = c.getstring (c.getcolumnindex ("password")); */public void rawquery (view view) {Cursor c= db.rawquery ("select * from Persondata where name=?", New string[]{        "DMJ"});              if (C.movetonext ()) {int Age=c.getint (C.getcolumnindex ("Age")); System.        Out.println (age); }   }}
The code for the 3.3DatabaseHelpter class is as follows:
<pre name= "code" class= "java" ><pre name= "code" class= "Java" >package Com.example.contentvaluespractice; Import Android.content.context;import Android.database.sqlite.sqlitedatabase;import Android.database.sqlite.sqliteopenhelper;public class Databasehelper extends Sqliteopenhelper {private static final S Tring db_name = "person.db"; Database name private static final int version = 1;    Database version Public Databasehelper (context context) {Super (context, db_name, NULL, version);        } @Override public void OnCreate (Sqlitedatabase db) {//This method will only execute if the getwritabledatabase () or Getreadabledatabase () method is invoked String sql = "CREATE TABLE Persondata (" + "ID integer primary key," + "n                 Ame varchar () NOT NULL, "+" age Integer, "+" Birthday date) ";    Db.execsql (SQL); }//If the Database_version value is changed to 2 and the system discovers that the existing database version is different, the Onupgrade @Override public void is called Onupgrade(sqlitedatabase db, int oldversion, int newversion) {Db.execsql ("...      "); }}
4.Methods for Cursors

Method Name Method Description
GetCount () Total number of records
IsFirst () Determine if the first record
Islast () Determine if the last record
Movetofirst () Move to the first record
Movetolast () Move to the last record
Move (int offset) Move to the specified record
MoveToNext () Move to scare a record
Movetoprevious () Move to previous record
Getcolumnindex (String columnName) Gets the int type value of the specified column index

5 precautions for using contenvalues

A construction method of insert

Public long Insert (string table, String nullcolumnhack, contentvalues values)

Table

The name of the table to insert data into

Values

The Contentvalues object, similar to a map, stores values in the form of key-value pairs.

Nullcolumnhack

when the values parameter is empty or there is no content in it, insert will fail (the underlying database does not allow inserting a blank line), in order to prevent this, specify a column name here, then if you find the behavior to be inserted empty row, The value of the column name that you specify is set to null and then inserted into the database. by observing the Insertwithonconflict method of the source code, you can see that when the Contentvalues type of data initialvalues is null or size<=0, The Nullcolumnhack setting is added to the SQL statement.

If you do not add Nullcolumnhack, the final result of the SQL statement will be similar to insert into TableName () values (NULL), which is not allowed.

If you add a nullcolumnhack, the SQL statement will become insert into TableName (nullcolumnhack) values (null);







Sqlitedatabase Database Operation detailed

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.