Project Source Download
Https://github.com/Wang-Jun-Chao/AndroidProjects
SQLite database
Lightweight relational database
The api:sqliteopenhelper to use to create the database
You must define a construction method:
//arg1:数据库文件的名字
//arg2:游标工厂
//arg3:数据库版本
public MyOpenHelper(Context context, String name, CursorFactory factory, int version){}
Called when a database is created: OnCreate method
Called when the database is upgraded: Onupgrade method
Creating a Database
MyOpenHelper oh = MyOpenHelper(getContext(), , , );
SQLiteDatabase db = oh.getWritableDatabase();
Getwritabledatabase (): Open a writable database
Getreadabledatabase (): Open a read-only database when disk space is low, otherwise open a writable database
Create a table when you create a database
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(" person (_id autoincrement,
name (), phone (), money ())
Database additions and deletions to check
SQL statement
* person (name, phone, money) (, , );
* person name = _id = ;
* person money = name = ;
* name, phone person name = ;
Execute SQL statement implementation and deletion and change check
db.execSQL(, []{, , });
Cursor cs = db.rawQuery(, []{});
This method is called before the test method executes
() Exception {
.setUp();
oh = MyOpenHelper(getContext(), , , );
}
Use API to implement additions and deletions
Insert
ContentValues cv = ContentValues();
cv.put(, );
cv.put(, );
cv.put(, );
i = db.insert(, , cv);
Delete
i = db.(, , String[]{, });
Modify
ContentValues cv = ContentValues();
cv.put(, );
i = db.update(, cv, , []{});
More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/OS/extra/
Inquire
Cursor cs = db.query(, []{, }, , []{}, , , );
(cs.moveToNext()){
name = cs.getString(cs.getColumnIndex());
money = cs.getString(cs.getColumnIndex());
System.out.println(name + + money);
}
Transaction
Ensure that multiple SQL statements succeed at the same time or fail at the same time
Most common cases: bank transfers
Transaction API
try {
dbbeginTransaction();
dbsetTransactionSuccessful();
} finally{
dbendTransaction();
}
Display data from the database to the screen
Arbitrarily insert some data
Define Business Bean:Person.java
Read all data from the database
Cursor cs = db.query(, , , , , , );
(cs.moveToNext()){
name = cs.getString(cs.getColumnIndex());
phone = cs.getString(cs.getColumnIndex());
money = cs.getString(cs.getColumnIndex());
Person p = Person(name, phone, money);
people.add(p);
}
Display the data from the collection to the screen
LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
(Person p : people){
TextView tv = TextView();
tv.setText(p.toString());
ll.addView(tv);
}
Page-Search
Cursor cs = db.query(, , , , , , , );