Sqlitedatabase class:
I. Manipulating databases with SQL statements
Sqlitedatabase db = Openorcreatedatabase ("database.db", mode_private,null);//(database name, permissions, Data Factory)
Db.execsql ("CREATE table if not exists USERTB (_id integer primary key autoincrement,name text not null,age integer not nul L,sex text not NULL);//execute any SQL statement
Db.execsql ("INSERT into USERTB (name,sex,age) VALUES (' Zhang San ', ' female ', 18)");//Insert Data
cursor: Cursor interface, provides methods for traversing query results, such as Move pointer method Move (), Get column value Method GetString () and other common methods:
-getcount () total number of records
-isfirst () Determines whether the first record
-islast () determines whether the last record
-movetofirst () moves to the first record
-movetolast () moves to the last record
-move (int Offset) moves to the specified record
-movetonext () moves to the next record
-movetoprevious () moves to the previous record
-getcolumnindexorthrow (String columnName) get column index by column name
-getint (int columnindex) gets the int type value of the specified column index
-getstring (int columnindex) Gets the string type value of the specified column index
Cursor c=db.rawquery ("Select*from table", null);
if (c!=null) {
while (C.movetonext ()) {}
}
PackageCom.example.sqlitetest1;ImportAndroid.database.Cursor;Importandroid.database.sqlite.SQLiteDatabase;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.util.Log; Public classMainactivityextendsappcompatactivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); //each program has its own database, which is not interfered by default//Create a database and openSqlitedatabase db=openorcreatedatabase ("USERTB", Mode_private,NULL); String sqlcom= "CREATE table if not exists USERTB (_id integer primary key autoincrement,name text,age integer,sex text)"; //Execute SQL statementDb.execsql (sqlcom); //inserting data into the databaseDb.execsql ("INSERT into USERTB (name,age,sex) VALUES (' Zhang San ', 18, ' female ')"); Db.execsql ("INSERT into USERTB (name,age,sex) VALUES (' Zhang San ', 20, ' Male ')"); Db.execsql ("INSERT into USERTB (name,age,sex) VALUES (' John Doe ', 21, ' female ')"); //EnquiryCursor cs=db.rawquery ("SELECT * from USERTB",NULL); if(cs!=NULL){ while(Cs.movetonext ()) {LOG.I ("Info", "ID:" +cs.getstring (Cs.getcolumnindex ("_id"))); LOG.I ("Info", "Name:" +cs.getstring (Cs.getcolumnindex ("name"))); LOG.I (' Info ', ' Age: ' +cs.getstring (Cs.getcolumnindex ("Age"))); LOG.I ("Info", "Sex:" +cs.getstring (Cs.getcolumnindex ("Sex"))); LOG.I ("Info", "--------------------------------------------"); } cs.close (); } db.close (); }}
Two. Manipulating databases with built-in functions
1. Contentvalues class
stores a set of values that can be processed by contentresolver, and it can be understood that its objects store multiple key-value pairs
2. Inserting a database using contentvalues and built-in functions
contentvalues values = new Contentvalues ();
values.put ("name", "zhang76");
values.put ("Sex", "man");
values.put ("age", +);
Sqlitedatabase.insert ("Studentdb", null, values);
values can be emptied and stored again.
values.clear ();
values.put ("name", "Zhang San");
values.put ("Sex", "man");
values.put ("age", +);
Sqlitedatabase.insert ("Studentdb", null, values);
3. Updates and deletions
sqlitedatabase.update ("Stutb", Values, "_id" >?,new string[]{"1"});//Change the gender of all id>1 into female;
sqlitedatabase.delete ("Stutb", "Name like", New string[]{"% three"});//delete all people with "three" in their names
4. All column names can be obtained by getcolumnnames () of the cursor class
if (cursors!=null) {
string[] ColumnNames = Cursor.getcolumnnames ();
while (Cursor.movetonext ()) {//movetonext () can be moved to the next line
for (String columnname:columnnames) {
LOG.I (TAG, Cursor.getstring (Cursor.getcolumnindex (ColumnName)));
}
}
Cursor.close ();//close cursor
}
Sqlitedatabase.close ();
PackageCom.example.sqlitetest2;Importandroid.content.ContentValues;ImportAndroid.database.Cursor;Importandroid.database.sqlite.SQLiteDatabase;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.util.Log; Public classMainactivityextendsappcompatactivity {Private Static FinalString tablename= "USERTB"; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Sqlitedatabase DB2=openorcreatedatabase ("db", Mode_private,NULL); String sqlcom= "CREATE table if not exists" +tablename+ "(_id Integer primary key autoincrement,name text,age integer,sex text)"; Db2.execsql (sqlcom); Contentvalues Values=Newcontentvalues (); Values.put ("Name", "Zhang San"); Values.put ("Age", 21); Values.put ("Sex", "male"); Db2.insert (TABLENAME,NULL, values); Values.clear (); Values.put ("Name", "John Doe"); Values.put ("Age", 24); Values.put ("Sex", "female"); Db2.insert (TABLENAME,NULL, values); Values.clear (); Values.put ("Name", "Harry"); Values.put ("Age", 19); Values.put ("Sex", "male"); Db2.insert (TABLENAME,NULL, values); Values.clear (); Values.put ("Name", "Zhang Si"); Values.put ("Age", 19); Values.put ("Sex", "female"); Db2.insert (TABLENAME,NULL, values); Values.clear (); Values.put ("Sex", "female"); //change the gender of id>3 to femaleDb2.update (Tablename,values, "_ID>??",Newstring[]{"3"}); //Remove the person with "three" in the nameDb2.delete (TABLENAME, "name like?",Newstring[]{"% three"}); //EnquiryCursor Cs=db2.query (TABLENAME,NULL, "_ID>?",Newstring[]{"0"},NULL,NULL, "name");//find out the value of id>0, that is, all if(cs!=NULL) {string[] columnnames=cs.getcolumnnames ();//query out all the fields while(Cs.movetonext ()) { for(String columnname:columnnames) {log.i ("Info", Cs.getstring (Cs.getcolumnindex (ColumnName))); }} cs.close (); } db2.close (); }}
Sqliteopenhelper class:
Sqliteopenhelper help class for creating and Upgrading databases.
Implement two methods: The OnCreate () method is used to implement the database creation, Onupgrade () to implement the upgrade database
@Override//When the database is first created, it is generally used to build the library/table-building operations
public void OnCreate (Sqlitedatabase db) {
TODO auto-generated method stubs
Db.execsql ("CREATE table if not exists STUTB (_id integer primary key autoincrement,name text not null,sex text not Null,ag e integer NOT null) ");
Db.execsql ("INSERT into STUTB (name,sex,age) VALUES (' Zhang San ', ' female ', 18)");
}
@Override//automatically executes when the version of the database changes
public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {
TODO auto-generated method stubs
}
Demo:
Myopenhelper.class:
PackageCom.example.sqlitetest3;ImportAndroid.content.Context;Importandroid.database.sqlite.SQLiteDatabase;ImportAndroid.database.sqlite.SQLiteOpenHelper;/*** Created by Xch on 2016/9/19.*/ Public classMyopenhelperextendssqliteopenhelper{Private Static FinalString tablename= "Stu"; PublicMyopenhelper (context context, String name, Sqlitedatabase.cursorfactory factory,intversion) { Super(context, name, Factory, version); } @Override//called when the database is first created, typically used to create a database creation table Public voidonCreate (Sqlitedatabase db) {String sqlcom= "CREATE table if not exists" +tablename+ "(_id Integer primary key autoincrement,name text,age integer,sex text)"; Db.execsql (sqlcom); Db.execsql ("INSERT INTO" +tablename+ "(name,sex,age) VALUES (' Yang ', ' Male ', 20)"); } @Override//called when the version is updated Public voidOnupgrade (Sqlitedatabase db,intOldversion,intnewversion) { }}
Mainactivity.class
PackageCom.example.sqlitetest3;ImportAndroid.database.Cursor;Importandroid.database.sqlite.SQLiteDatabase;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.util.Log; Public classMainactivityextendsappcompatactivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Myopenhelper Helper=NewMyopenhelper (mainactivity. This, "Stu",NULL, 1); Helper.getreadabledatabase ();//gets a read-only database that cannot be written, cannot be updated, and can only be queriedSqlitedatabase database=helper.getwritabledatabase (); Cursor CS=database.rawquery ("Select * from Stu",NULL); if(cs!=NULL) {string[] colmnnames=Cs.getcolumnnames (); while(Cs.movetonext ()) { for(String cln:colmnnames) {log.i ("Info", "ColumnNames:" +cs.getstring (Cs.getcolumnindex (CLN))); }} cs.close (); } database.close (); }}
Android Learning Summary--sqlite