SQLite應用實例


DatabaseHelper.java

/** * 繼承SQLiteOpenHelper * * @author Harvey * */
public class DatabaseHelper extends SQLiteOpenHelper { /** * 數據庫名稱 /.db可有可無 */
    public static final String DATABASE_NAME = "test.db"; /** * 數據庫版本,版本號不能為0 */
    public static final int DATABASE_VERSION = 1; /** * 構造方法 * * @param context */
    public DatabaseHelper(Context context) { // CursorFactory設置為null,使用默認值
        this(context, DATABASE_NAME, null, DATABASE_VERSION); } /** * 必須要有此構造方法 * * @param context * 代表應用的上下文 * @param name * 代表數據庫的名稱 * @param factory * 代表記錄集游標工廠,是專門用來生成記錄集游標,記錄集游標是對查詢結果進行迭代的 * @param version * 代表數據庫的版本,如果以后升級軟件的時候,需要更改 */
    public DatabaseHelper(Context context, String name, CursorFactory factory, int version) { // 必須通過super調用父類當中的構造函數
        super(context, name, factory, version); } /** * 在用戶第一次使用軟件時,會創建數據庫,而該方法在數據庫初次創建時被調用,此方法中特別適合 * 生成數據庫表的結構,它只會被調用一次,它的唯一一個參數是操作數據庫的工具類,這個 * 工具類提供了對數據的添、刪、改、查等方法,用這個類實現對SQL語句的執行 */ @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE person (personid INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR(20), age INTEGER)"); } /** * version版本號發生改變時,此方法會被調用,在這個方法中比較適合實現軟件更新時修改數據庫表結構的工作 */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // 數據庫更新的語句
        db.execSQL("ALTER TABLE person ADD COLUMN other STRING"); } }

 Person.java

public class Person { /** * id */
    private Integer id; /** * name */
    private String name; /** * age */
    private Integer age; public Person() {
}
public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "id:" + id + "\nage:" + age + "\nname:" + name; } }

SQLiteTestActivity.java(第一種方法)

/** * 數據庫使用測試 * * @author admin * */
public class SQLiteTestActivity extends Activity implements OnClickListener { private Button addBtn, addListBtn, delBtn, updateBtn, queryBtn, countBtn, pagingBtn, otherBtn; private TextView text; private DatabaseHelper databaseHelper; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); } private void init() { addBtn = (Button) findViewById(R.id.add); addListBtn = (Button) findViewById(R.id.addList); delBtn = (Button) findViewById(R.id.delete); updateBtn = (Button) findViewById(R.id.update); queryBtn = (Button) findViewById(R.id.query); countBtn = (Button) findViewById(R.id.count); pagingBtn = (Button) findViewById(R.id.paging); otherBtn = (Button) findViewById(R.id.other);
// 設置監聽 addBtn.setOnClickListener(this); addListBtn.setOnClickListener(this); delBtn.setOnClickListener(this); updateBtn.setOnClickListener(this); queryBtn.setOnClickListener(this); countBtn.setOnClickListener(this); pagingBtn.setOnClickListener(this); otherBtn.setOnClickListener(this); text = (TextView) findViewById(R.id.text); databaseHelper = new DatabaseHelper(this); } @Override public void onClick(View v) { /** * 添加對象 */ if (v.equals(addBtn)) { Person person = new Person(); person.setName("Eric"); person.setAge(23); addData(person); } /** * 添加對象集合 */ if (v.equals(addListBtn)) { ArrayList<Person> personList = new ArrayList<Person>(); Person person = new Person(); person.setName("Tom"); person.setAge(20); personList.add(person); Person person1 = new Person(); person1.setName("Jack"); person1.setAge(21); personList.add(person1); Person person2 = new Person(); person2.setName("Harvey"); person2.setAge(22); personList.add(person2); addData(personList); } /** * 刪除數據 */ if (v.equals(delBtn)) { deleteData(1); } /** * 更新數據 */ if (v.equals(updateBtn)) { Person person = new Person(); person.setId(2); person.setName("Bob"); person.setAge(35); updateData(person); } /** * 查詢數據 */ if (v.equals(queryBtn)) { queryData(3); } /** * 數據總數 */ if (v.equals(countBtn)) { System.out.println("查詢總數=====" + countData()); } /** * 分頁 */ if (v.equals(pagingBtn)) { getScrollData(0, 3); } if (v.equals(otherBtn)) { other(); } } /** * 添加對象 */ private void addData(Person person) { SQLiteDatabase db = databaseHelper.getWritableDatabase();// 創建或者打開一個可寫數據庫 // 插入數據 db.execSQL("INSERT INTO person(name, age) VALUES(?,?)", new Object[] { person.getName(), person.getAge() }); Log.i("SQLiteTestActivity", "name:" + person.getName() + "\nage:" + person.getAge()); } /** * 添加對象集合 * * @param personList */ private void addData(ArrayList<Person> personList) { SQLiteDatabase db = databaseHelper.getWritableDatabase();// 創建或者打開一個可寫數據庫 db.beginTransaction(); // 開始事務 try { for (Person person : personList) { db.execSQL("INSERT INTO person(name, age) VALUES(?, ?)", new Object[] { person.getName(), person.getAge() }); Log.i("SQLiteTestActivity", "name:" + person.getName() + "\nage:" + person.getAge()); } db.setTransactionSuccessful(); // 設置事務成功完成 } finally { db.endTransaction(); // 結束事務 } } /** * 刪除數據 * * @param id */ private void deleteData(Integer id) { SQLiteDatabase db = databaseHelper.getWritableDatabase();// 創建或者打開一個可寫數據庫 db.execSQL("delete from person where personid=?", new Object[] { id }); } /** * 更新數據 */ private void updateData(Person person) { SQLiteDatabase db = databaseHelper.getWritableDatabase(); db.execSQL("update person set name=?,age=? where personid=?", new Object[] { person.getName(), person.getAge(), person.getId() }); } /** * 查詢數據 */ private void queryData(Integer id) { SQLiteDatabase db = databaseHelper.getReadableDatabase();// 創建或者打開一個查詢數據庫 Cursor cursor = db.rawQuery("select * from person where personid=?", new String[] { String.valueOf(id) }); // 迭代記錄集 if (cursor.moveToNext()) { Person person = new Person(); person.setId(cursor.getInt(cursor.getColumnIndex("personid"))); person.setName(cursor.getString(cursor.getColumnIndex("name"))); person.setAge(cursor.getInt(cursor.getColumnIndex("age"))); // 將查到的字段,放入person System.out.println(person.toString()); text.setText(person.toString()); } cursor.close();// 游標關閉 } /** * 獲取記錄總數 * * @return */ private long countData() { SQLiteDatabase db = databaseHelper.getReadableDatabase(); // 沒有占位符參數的話,直接用null Cursor cursor = db.rawQuery("select * from person", null); int count = cursor.getCount(); cursor.close(); return count; } /** * 分頁 * * @param offset * @param count */ private void getScrollData(int offset, int count) { ArrayList<Person> persons = new ArrayList<Person>(); SQLiteDatabase db = databaseHelper.getReadableDatabase(); // offset開始索引 // count 記錄條數 Cursor cursor = db.rawQuery("select personid,name,age from person limit ?,?", new String[] { String.valueOf(offset), String.valueOf(count) }); while (cursor.moveToNext()) { Person person = new Person(); person.setId(cursor.getInt(cursor.getColumnIndex("personid"))); person.setName(cursor.getString(cursor.getColumnIndex("name"))); person.setAge(cursor.getInt(cursor.getColumnIndex("age"))); persons.add(person); Log.i("SQLiteTestActivity", "name:" + person.getName() + "\nage:" + person.getAge()); } System.out.println("大小================" + persons.size()); cursor.close(); } private void other() { Intent intent = new Intent(SQLiteTestActivity.this, OtherActivity.class); startActivity(intent); } }

OtherActivity.java(第二種方法)

public class OtherActivity extends Activity implements OnClickListener { private Button addBtn, addListBtn, delBtn, updateBtn, queryBtn, countBtn, pagingBtn; private TextView text; private DatabaseHelper databaseHelper; private ArrayList<Person> personList; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.other); init(); } private void init() { addBtn = (Button) findViewById(R.id.add); addListBtn = (Button) findViewById(R.id.addList); delBtn = (Button) findViewById(R.id.delete); updateBtn = (Button) findViewById(R.id.update); queryBtn = (Button) findViewById(R.id.query); countBtn = (Button) findViewById(R.id.count); pagingBtn = (Button) findViewById(R.id.paging); // 設置監聽
        addBtn.setOnClickListener(this); addListBtn.setOnClickListener(this); delBtn.setOnClickListener(this); updateBtn.setOnClickListener(this); queryBtn.setOnClickListener(this); countBtn.setOnClickListener(this); pagingBtn.setOnClickListener(this); text = (TextView) findViewById(R.id.text); databaseHelper = new DatabaseHelper(this); } @Override public void onClick(View v) { /** * 添加對象 */
        if (v.equals(addBtn)) { Person person = new Person(); person.setName("Eric"); person.setAge(3); addData(person); } /** * 添加對象集合 */
        if (v.equals(addListBtn)) { personList = new ArrayList<Person>(); Person person = new Person(); person.setName("Tom"); person.setAge(2); personList.add(person); Person person1 = new Person(); person1.setName("Jack"); person1.setAge(3); personList.add(person1); Person person2 = new Person(); person2.setName("Harvey"); person2.setAge(6); personList.add(person2); addData(personList); } /** * 刪除數據 */
        if (v.equals(delBtn)) { deleteData(1); } /** * 更新數據 */
        if (v.equals(updateBtn)) { Person person = new Person(); person.setId(3); person.setName("Bob"); person.setAge(0); updateData(person); } /** * 查詢數據 */
        if (v.equals(queryBtn)) { queryData(3); } /** * 數據總數 */
        if (v.equals(countBtn)) { System.out.println("查詢個數=====" + countData()); } /** * 分頁 */
        if (v.equals(pagingBtn)) { getScrollData(0, 3); } } /** * 添加數據 */
    private void addData(Person person) { SQLiteDatabase db = databaseHelper.getWritableDatabase();// 創建或者打開一個可寫數據庫
        ContentValues contentValues = new ContentValues(); contentValues.put("name", person.getName()); contentValues.put("age", person.getAge()); db.insert("person", null, contentValues); } /** * 添加集合數據 * * @param personList */
    private void addData(ArrayList<Person> personList) { SQLiteDatabase db = databaseHelper.getWritableDatabase();// 創建或者打開一個可寫數據庫
        db.beginTransaction(); // 開始事務
        try { for (Person person : personList) { ContentValues contentValues = new ContentValues(); contentValues.put("name", person.getName()); contentValues.put("age", person.getAge()); db.insert("person", null, contentValues); Log.i("SQLiteTestActivity", "name:" + person.getName() + "\nage:" + person.getAge()); } db.setTransactionSuccessful(); // 設置事務成功完成
 } finally { db.endTransaction(); // 結束事務
 } } /** * 刪除數據 * * @param id */
    private void deleteData(Integer id) { SQLiteDatabase db = databaseHelper.getWritableDatabase();// 創建或者打開一個可寫數據庫
        db.delete("person", "personid=?", new String[] { String.valueOf(id) }); } /** * 更新數據 */
    private void updateData(Person person) { ContentValues contentValues = new ContentValues(); contentValues.put("name", person.getName()); contentValues.put("age", person.getAge()); SQLiteDatabase db = databaseHelper.getWritableDatabase(); /** * 第一個參數表示表名 /第二個參數表示更新的數據/第三個參數表示SQL語句的中條件部分的語句 /第四個參數占位符的值 */ db.update("person", contentValues, "personid=?", new String[] { String.valueOf(person.getId()) }); } /** * 查詢數據 */
    private void queryData(Integer id) { SQLiteDatabase db = databaseHelper.getReadableDatabase();// 創建或者打開一個查詢數據庫
        /** * 第一個參數表示表名 /第二個參數表示查找需要返回的字段/第三個參數表示SQL語句的中條件部分的語句 * /第四個參數占位符的值/第五個參數表示分組 * 可設為null/第六個參數表示SQL語句中的having,可設為null/第七個參數表示結果的排序,可設為null */ Cursor cursor = db.query("person", new String[] { "personid", "name", "age" }, "personid=?", new String[] { String.valueOf(id) }, null, null, null); // 迭代記錄集
        if (cursor.moveToNext()) { Person person = new Person(); person.setId(cursor.getInt(cursor.getColumnIndex("personid"))); person.setName(cursor.getString(cursor.getColumnIndex("name"))); person.setAge(cursor.getInt(cursor.getColumnIndex("age"))); // 將查到的字段,放入person
 System.out.println(person.toString()); text.setText(person.toString()); } cursor.close();// 游標關閉
 } /** * 獲取記錄總數 * * @return
     */
    private long countData() { SQLiteDatabase db = databaseHelper.getReadableDatabase(); Cursor cursor = db.query("person", new String[] { "*" }, null, null, null, null, null); int count = cursor.getCount(); cursor.close();// 游標關閉
        return count; } /** * 分頁 * * @param offset * @param count */
    private void getScrollData(int offset, int count) { ArrayList<Person> persons = new ArrayList<Person>(); SQLiteDatabase db = databaseHelper.getReadableDatabase(); Cursor cursor = db.query("person", new String[] { "personid", "name", "age" }, null, null, null, null, null, offset + "," + count); while (cursor.moveToNext()) { Person person = new Person(); person.setId(cursor.getInt(cursor.getColumnIndex("personid"))); person.setName(cursor.getString(cursor.getColumnIndex("name"))); person.setAge(cursor.getInt(cursor.getColumnIndex("age"))); persons.add(person); Log.i("OtherActivity", "name:" + person.getName() + "\nage:" + person.getAge()); } System.out.println("大小================" + persons.size()); cursor.close(); } }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM