entities(實體類)類:
public class Person {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Person() {
super();
// TODO Auto-generated constructor stub
}
public Person(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
資料庫幫助類:
/**
* 資料庫幫助類, 用于建立和管理資料庫的.
*/
public class PersonSQLiteOpenHelper extends SQLiteOpenHelper {
private static final String TAG = "PersonSQLiteOpenHelper";
/**
* 資料庫的構造函數
* @param context
*
* name 資料庫名稱
* factory 遊标工程
* version 資料庫的版本号 不可以小于1
*/
public PersonSQLiteOpenHelper(Context context) {
super(context, "itheima28.db", null, );
}
/**
* 資料庫第一次建立時回調此方法.
* 初始化一些表
*/
@Override
public void onCreate(SQLiteDatabase db) {
// 操作資料庫
String sql = "create table person(_id integer primary key, name varchar(20), age integer);";
db.execSQL(sql); // 建立person表
}
/**
* 資料庫的版本号更新時回調此方法,
* 更新資料庫的内容(删除表, 添加表, 修改表)
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(oldVersion == && newVersion == ) {
Log.i(TAG, "資料庫更新啦");
// 在person表中添加一個餘額列balance
db.execSQL("alter table person add balance integer;");
}
}
使用SQL語句實作增删改查:
public class PersonDao {
private PersonSQLiteOpenHelper mOpenHelper; // 資料庫的幫助類對象
public PersonDao(Context context) {
mOpenHelper = new PersonSQLiteOpenHelper(context);
}
/**
* 添加到person表一條資料
* @param person
*/
public void insert(Person person) {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
if(db.isOpen()) { // 如果資料庫打開, 執行添加的操作
// 執行添加到資料庫的操作
db.execSQL("insert into person(name, age) values(?, ?);", new Object[]{person.getName(), person.getAge()});
db.close(); // 資料庫關閉
}
}
/**
* 更據id删除記錄
* @param id
*/
public void delete(int id) {
SQLiteDatabase db = mOpenHelper.getWritableDatabase(); // 獲得可寫的資料庫對象
if(db.isOpen()) { // 如果資料庫打開, 執行添加的操作
db.execSQL("delete from person where _id = ?;", new Integer[]{id});
db.close(); // 資料庫關閉
}
}
/**
* 根據id找到記錄, 并且修改姓名
* @param id
* @param name
*/
public void update(int id, String name) {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
if(db.isOpen()) { // 如果資料庫打開, 執行添加的操作
db.execSQL("update person set name = ? where _id = ?;", new Object[]{name, id});
db.close(); // 資料庫關閉
}
}
//查詢
public List<Person> queryAll() {
SQLiteDatabase db = mOpenHelper.getReadableDatabase(); // 獲得一個隻讀的資料庫對象
if(db.isOpen()) {
Cursor cursor = db.rawQuery("select _id, name, age from person;", null);
if(cursor != null && cursor.getCount() > ) {
List<Person> personList = new ArrayList<Person>();
int id;
String name;
int age;
while(cursor.moveToNext()) {
id = cursor.getInt(); // 取第0列的資料 id
name = cursor.getString(); // 取姓名
age = cursor.getInt(); // 取年齡
personList.add(new Person(id, name, age));
}
db.close();
return personList;
}
db.close();
}
return null;
}
/**
* 根據id查詢人
* @param id
* @return
*/
public Person queryItem(int id) {
SQLiteDatabase db = mOpenHelper.getReadableDatabase(); // 獲得一個隻讀的資料庫對象
if(db.isOpen()) {
Cursor cursor = db.rawQuery("select _id, name, age from person where _id = ?;", new String[]{id + ""});
if(cursor != null && cursor.moveToFirst()) {
int _id = cursor.getInt();
String name = cursor.getString();
int age = cursor.getInt();
db.close();
return new Person(_id, name, age);
}
db.close();
}
return null;
}
對第一種使用SQL語句實作CRUD進行測試:
public class TestCase extends AndroidTestCase {
private static final String TAG = "TestCase";
public void test() {
// 資料庫什麼時候建立
PersonSQLiteOpenHelper openHelper = new PersonSQLiteOpenHelper(getContext());
// 第一次連接配接資料庫時建立資料庫檔案. onCreate會被調用
openHelper.getReadableDatabase();
}
public void testInsert() {
PersonDao dao = new PersonDao(getContext());
dao.insert(new Person(, "冠希", ));
}
public void testDelete() {
PersonDao dao = new PersonDao(getContext());
dao.delete();
}
public void testUpdate() {
PersonDao dao = new PersonDao(getContext());
dao.update(, "鳳姐");
}
public void testQueryAll() {
PersonDao dao = new PersonDao(getContext());
List<Person> personList = dao.queryAll();
for (Person person : personList) {
Log.i(TAG, person.toString());
}
}
public void testQueryItem() {
PersonDao dao = new PersonDao(getContext());
Person person = dao.queryItem();
Log.i(TAG, person.toString());
}
public void testTransaction() {
PersonSQLiteOpenHelper openHelper = new PersonSQLiteOpenHelper(getContext());
SQLiteDatabase db = openHelper.getWritableDatabase();
if(db.isOpen()) {
try {
// 開啟事務
db.beginTransaction();
// 1. 從張三賬戶中扣1000塊錢
db.execSQL("update person set balance = balance - 1000 where name = 'zhangsan';");
// ATM機, 挂掉了.
// int result = 10 / 0;
// 2. 向李四賬戶中加1000塊錢
db.execSQL("update person set balance = balance + 1000 where name = 'lisi';");
// 标記事務成功
db.setTransactionSuccessful();
} finally {
// 停止事務
db.endTransaction();
}
db.close();
}
}
//測試插入資料的時候開啟事務增加效率
public void testTransactionInsert() {
PersonSQLiteOpenHelper openHelper = new PersonSQLiteOpenHelper(getContext());
SQLiteDatabase db = openHelper.getWritableDatabase();
if(db.isOpen()) {
// 1. 記住目前的時間
long start = System.currentTimeMillis();
// 2. 開始添加資料
try {
db.beginTransaction();
for (int i = ; i < ; i++) {
db.execSQL("insert into person(name, age, balance) values('wang" + i + "', " + ( + i) + ", " + ( + i) + ")");
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
// 3. 記住結束時間, 計算耗時時間
long end = System.currentTimeMillis();
long diff = end - start;
Log.i(TAG, "耗時: " + diff + "毫秒");
db.close();
}
}
使用API實作資料庫的CRUD:
public class PersonDao2 {
private static final String TAG = "PersonDao2";
private PersonSQLiteOpenHelper mOpenHelper; // 資料庫的幫助類對象
public PersonDao2(Context context) {
mOpenHelper = new PersonSQLiteOpenHelper(context);
}
/**
* 添加到person表一條資料
* @param person
*/
public void insert(Person person) {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
if(db.isOpen()) { // 如果資料庫打開, 執行添加的操作
ContentValues values = new ContentValues();
values.put("name", person.getName()); // key作為要存儲的列名, value對象列的值
values.put("age", person.getAge());
long id = db.insert("person", "name", values);
Log.i(TAG, "id: " + id);
db.close(); // 資料庫關閉
}
}
/**
* 更據id删除記錄
* @param id
*/
public void delete(int id) {
SQLiteDatabase db = mOpenHelper.getWritableDatabase(); // 獲得可寫的資料庫對象
if(db.isOpen()) { // 如果資料庫打開, 執行添加的操作
String whereClause = "_id = ?";
String[] whereArgs = {id + ""};
int count = db.delete("person", whereClause, whereArgs);
Log.i(TAG, "删除了: " + count + "行");
db.close(); // 資料庫關閉
}
}
/**
* 根據id找到記錄, 并且修改姓名
* @param id
* @param name
*/
public void update(int id, String name) {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
if(db.isOpen()) { // 如果資料庫打開, 執行添加的操作
ContentValues values = new ContentValues();
values.put("name", name);
int count = db.update("person", values, "_id = ?", new String[]{id + ""});
Log.i(TAG, "修改了: " + count + "行");
db.close(); // 資料庫關閉
}
}
public List<Person> queryAll() {
SQLiteDatabase db = mOpenHelper.getReadableDatabase(); // 獲得一個隻讀的資料庫對象
if(db.isOpen()) {
String[] columns = {"_id", "name", "age"}; // 需要的列
String selection = null; // 選擇條件, 給null查詢所有
String[] selectionArgs = null; // 選擇條件的參數, 會把選擇條件中的? 替換成資料中的值
String groupBy = null; // 分組語句 group by name
String having = null; // 過濾語句
String orderBy = null; // 排序
Cursor cursor = db.query("person", columns, selection, selectionArgs, groupBy, having, orderBy);
int id;
String name;
int age;
if(cursor != null && cursor.getCount() > ) {
List<Person> personList = new ArrayList<Person>();
while(cursor.moveToNext()) { // 向下移一位, 知道最後一位, 不可以往下移動了, 停止.
id = cursor.getInt();
name = cursor.getString();
age = cursor.getInt();
personList.add(new Person(id, name, age));
}
db.close();
return personList;
}
db.close();
}
return null;
}
/**
* 根據id查詢人
* @param id
* @return
*/
public Person queryItem(int id) {
SQLiteDatabase db = mOpenHelper.getReadableDatabase(); // 獲得一個隻讀的資料庫對象
if(db.isOpen()) {
String[] columns = {"_id", "name", "age"}; // 需要的列
String selection = "_id = ?"; // 選擇條件, 給null查詢所有
String[] selectionArgs = {id + ""}; // 選擇條件的參數, 會把選擇條件中的? 替換成資料中的值
String groupBy = null; // 分組語句 group by name
String having = null; // 過濾語句
String orderBy = null; // 排序
Cursor cursor = db.query("person", columns, selection, selectionArgs, groupBy, having, orderBy);
if(cursor != null && cursor.moveToFirst()) { // cursor對象不為null, 并且可以移動到第一行
int _id = cursor.getInt();
String name = cursor.getString();
int age = cursor.getInt();
db.close();
return new Person(_id, name, age);
}
db.close();
}
return null;
}
對使用API方式實作CRUD進行測試:
public class TestCase2 extends AndroidTestCase {
private static final String TAG = "TestCase";
public void test() {
// 資料庫什麼時候建立
PersonSQLiteOpenHelper openHelper = new PersonSQLiteOpenHelper(getContext());
// 第一次連接配接資料庫時建立資料庫檔案. onCreate會被調用
openHelper.getReadableDatabase();
}
public void testInsert() {
PersonDao2 dao = new PersonDao2(getContext());
dao.insert(new Person(, "zhouqi", ));
}
public void testDelete() {
PersonDao2 dao = new PersonDao2(getContext());
dao.delete();
}
public void testUpdate() {
PersonDao2 dao = new PersonDao2(getContext());
dao.update(, "fengjie");
}
public void testQueryAll() {
PersonDao2 dao = new PersonDao2(getContext());
List<Person> personList = dao.queryAll();
for (Person person : personList) {
Log.i(TAG, person.toString());
}
}
public void testQueryItem() {
PersonDao2 dao = new PersonDao2(getContext());
Person person = dao.queryItem();
Log.i(TAG, person.toString());
}
Linearlayout的清單展示:
布局檔案:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/ll_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
業務邏輯實作:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout llList = (LinearLayout) findViewById(R.id.ll_list);
PersonDao dao = new PersonDao(this);
List<Person> personList = dao.queryAll();
if(personList != null) {
TextView tv;
for (Person person : personList) {
// 向線性布局中添加一個textview
tv = new TextView(this);
tv.setText(person.toString());
tv.setTextSize();
llList.addView(tv);
}
}
}