第十二章:Android數據存儲(下)

1、SQLite介紹php

提到數據存儲問題,數據庫是不得不提的。數據庫是用來存儲關係型數據的不二利器。Android爲開發者提供了強大的數據庫支持,能夠用來輕鬆地構造基於數據庫的應用。Android的數據庫應用,依託於當下最流行的開源嵌入式數據庫SQLite。在Android中,應用的數據庫文件是該應用私有的,存儲在應用數據目錄下的databases子目錄內。從代碼結構來看,Android的數據庫實現能夠分紅兩個層次,在底層經過C++調用SQLite的接口來執行SQL語句,並經過JNI向上暴露Java可訪問的接口。java

SQLite可視化工具:SQLite Expert Professional 3;android

2、Android訪問SQLitesql

主要步驟:

(1)建立某個類繼承SQLiteOpenHelper,並重寫
-- 帶Context參數的構造函數; //用來建立數據庫
-- onCreate(SQLiteDatabase db); //在建立數據庫時調用
-- onUpgrade(SQLiteDatabase db,int old,int newversion);  //數據庫版本更改時調用
(2)建立數據庫:SQLiteDatabase db = helper.getWritableDatabase();
(3)SQL語句:db.execSQL(String sql);
 
語句使用:

1.打開數據庫

 
SQLiteDatabase db = helper.getWritableDatabase();
SQLiteDatabase db = helper.getReadableDatabase(); //此函數內部其實也調用了getWritableDatabase()函數,即調用了此函數,也能夠寫數據
 

2.insert語句

 
(1)db.execSQL("insert into person(name,age) values(?,?)",new Object[]{"xiazdong",20});
(2)
ContentValues values = new ContentValues();
values.put("name","xiazdong");
values.put("age",20);
db.insert("tablename",null,values);

3.delete語句

 
(1)db.execSQL("delete from person where id=?",new Object[]{id});
(2)db.delete("tablename","id=?",new String[]{id+""});
 

4.update語句

 
(1)
db.exeSQL("update person set age=? where name=?",new Object[]{30,"xiazdong"});
(2)
ContentValues values = new ContentValues();
values.put("age",30);/*set子句*/
db.update("tablename",values,"name=?"/*where子句*/,new String[]{"xiazdong"}/*where子句參數*/);

5.query語句

 
(1)
Cursor cursor = db.rawQuery("select * from person where name=?",new Object[]{"xiazdong"});
while(cursor.moveToNext()){
    //int index = cursor.getColumnIndex(String name);//根據name得到索引
    //String name = cursor.getString(int index);    //根據索引得到值
    String name = cursor.getString(cursor.getColumnIndex("name")); 
}
(2)
Cursor cursor = db.query("tablename",null /*表示select * */,"name=?" /*where語句*/,new String[]{"xiazdong"},null/*group by 語句*/,null/*having 語句*/,null/*order by語句*/,null/*limit 語句*/);
 

6.分頁語句

 
Cursor cursor = db.rawQuery("select * from person limit ?,?",new Object[]{5,5});    //第一個5表示跳過5條記錄,下一個5爲查詢結果的記錄個數
while(cursor.moveToNext()){
    String name = cursor.getString(cursor.getColumnIndex("name")); 
}

7.得到記錄個數語句

 
(1)
Cursor cursor = db.rawQuery("select count(*) from person", null);
cursor.moveToFirst();
int count = cursor.getInt(0);
 
(2)
db.query("person",new String[]{"count(*)"},null,null,null,null,null,null);
 
 
 
 示例代碼:
MySQLiteOpenHelper.java:
package com.example.helloandroid;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class MySQLiteOpenHelper extends SQLiteOpenHelper {

    public MySQLiteOpenHelper(Context context, String name,
            CursorFactory factory, int version) {
        super(context, name, factory, version);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        
    }

}
View Code

DataBaseActivity.java數據庫

package com.example.helloandroid;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class DataBaseActivity extends Activity {
      private Button createDatabase, createTable, selectData, insertData,
      updateData, deleteDaata;
      private MySQLiteOpenHelper helper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_base);
        
        // 初始化按鈕
        createDatabase = (Button) findViewById(R.id.createDatabase);
        createTable = (Button) findViewById(R.id.createTable);
        selectData = (Button) findViewById(R.id.selectData);
        insertData = (Button) findViewById(R.id.insertData);
        updateData = (Button) findViewById(R.id.updateData);
        deleteDaata = (Button) findViewById(R.id.deleteDaata);
        
        
        helper = new MySQLiteOpenHelper(DataBaseActivity.this, "mydb.db",
                null, 1);
        
        /*
         * 建立數據庫
         */
        createDatabase.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                SQLiteDatabase sqlitedatabase = helper.getWritableDatabase();
                Toast.makeText(DataBaseActivity.this, "數據庫建立成功", 1000).show();

            }

        });
        
        /*
         * 建立表
         */
        createTable.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                SQLiteDatabase sqlitedatabase = helper.getWritableDatabase();
                // 建立表
                sqlitedatabase
                        .execSQL("create table student(id INTEGER PRIMARY KEY autoincrement,name text)");
                Toast.makeText(DataBaseActivity.this, "表建立成功", 1000).show();
            }
        });
        
        
        /*
         * 插入數據
         */

        insertData.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                SQLiteDatabase sqlitedatabase = helper.getWritableDatabase();
                sqlitedatabase
                        .execSQL("insert into student(name) values ('tinyphp')");
                Toast.makeText(DataBaseActivity.this, "插入數據成功", 1000).show();
            }
        });

        /*
         * 更新數據
         */
        updateData.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                SQLiteDatabase sqlitedatabase = helper.getWritableDatabase();
                sqlitedatabase
                        .execSQL("update student set name='monkey' where id='1'");
                Toast.makeText(DataBaseActivity.this, "數據更新成功", 1000).show();
            }
        });

        /*
         * 查詢數據
         */

        selectData.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                SQLiteDatabase sqlitedatabase = helper.getReadableDatabase();
                
                //參數:表名、查詢的列、查詢條件、查詢參數、查詢結果分組、分組結果限制、排序
                Cursor cursor = sqlitedatabase.query("student", new String[] {
                        "id", "name" }, "id=?", new String[] { "1" }, null,
                        null, null);
                String name=null;
                while(cursor.moveToNext()){
                    name =cursor.getString(cursor.getColumnIndex("name"));                    
                }
                Toast.makeText(DataBaseActivity.this, "查詢結果name爲:"+name, 1000).show();
            }
        });

        
        /*
         * 刪除數據
         * */
                
        deleteDaata.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                SQLiteDatabase sqlitedatabase =helper.getWritableDatabase();
                sqlitedatabase.delete("student", "id=?", new String[]{"1"});
                Toast.makeText(DataBaseActivity.this, "數據刪除成功", 1000).show();
            }
        });





    }
}
View Code

activity_data_base.xmlapp

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

     <Button
        android:id="@+id/createDatabase"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="建立數據庫" />
     
     <Button
        android:id="@+id/createTable"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="建立表" />
     
       <Button
        android:id="@+id/insertData"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="插入" />
       
       <Button
        android:id="@+id/updateData"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="更新" />

       <Button
           android:id="@+id/selectData"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:text="查詢" />
       
        <Button
        android:id="@+id/deleteDaata"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="刪除" />
</LinearLayout>
View Code

 效果圖:ide

相關文章
相關標籤/搜索