天天看點

SQLiteDatabase資料庫的使用

SQLite資料庫

Sqllite資料庫是Android系統內建的一個輕量級資料庫,是一個嵌入式的資料庫引擎,專門用于資源有限的裝置的資料操作。

SQLiteDatabase資料庫的使用步驟

擷取SQLiteDatabase對象

調用SQLiteDatabase方法執行sql語句

操作傳回的cursor結果

關閉SQLiteDatabase資料庫

Cursor的使用,可以移動指針到某行,移動成功傳回true,移動到指定行後,可通過getXXX()方法擷取指定列資料

SQLiteDatabase的事務

通過beginTransaction()開啟事務

通過endTransaction()送出或復原事務,具體送出或復原取決于SQLiteDatabase是否調用了setTransactionSuccessful()方法設定事務辨別,設定了的話事務執行成功則送出事務,否則復原。

SQLiteDatabase資料庫類

SQLiteDatabase代表一個資料庫檔案,隻要擷取該對象就可以對該資料庫檔案進行修改,

方法1建立資料庫

Static SQLiteDatabaseopenDatabase(String path, SQLiteDatabase.CursorFactory  factory,int flags);//打開path檔案所帶表的sqlLite資料庫// factory用于傳回cursor的工廠,null傳回預設的工廠

Static SQLiteDatabaseopenOrCreateDatabase(File file, SQLiteDatabase.CursorFactory  factory);//打開或建立(如果不存在)file檔案所代表的SqlLite資料庫

Static SQLiteDatabaseopenOrCreateDatabase(String path, SQLiteDatabase.CursorFactory  factory);//打開或建立(如果不存在)path檔案所代表的SqlLite資料庫

擷取sqlLite資料庫對象後就可以對資料庫進行增删改查,對于查詢的方法會傳回一個Cursor對象

方法2:建立資料庫

在實際開發中多使用SQLiteOpenHelper開發的子類打開資料庫,擷取資料庫對象。進行操作資料庫

SQLite資料庫的使用方法有insert(),update(),delete(),query()包含資料庫的增删改查

執行個體:

布局檔案

<?xmlversion="1.0"encoding="utf-8"?>

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical">

<LinearLayout

    android:layout_width="match_parent"

     android:layout_height="match_parent"

     android:orientation="vertical"

     android:layout_weight="1">

   <Buttonandroid:id="@+id/insertWord"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="添加單詞"/>

    <Buttonandroid:id="@+id/deleteWord"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="删除單詞"/>

    <Buttonandroid:id="@+id/updateWord"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="修改單詞"/>

    <Buttonandroid:id="@+id/queryWord"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="查詢單詞"/>

    <EditTextandroid:id="@+id/word"

        android:layout_width="match_parent"

        android:layout_height="40dp"

        android:hint="請輸入添加的詞"/>

    <EditTextandroid:id="@+id/note"

        android:layout_width="match_parent"

        android:layout_height="40dp"

        android:hint="請輸入添加的詞的注釋"/>

    <EditTextandroid:id="@+id/willChange"

        android:layout_width="match_parent"

        android:layout_height="40dp"

        android:hint="請輸入将被修改的詞"/>

    </LinearLayout>

    <LinearLayout

         android:layout_width="match_parent"

     android:layout_height="match_parent"

     android:orientation="vertical"

     android:layout_weight="3"

     >

    <ListView

        android:id="@+id/showWords"

        android:layout_width="match_parent"

     android:layout_height="wrap_content">

    </ListView>

    </LinearLayout>

</LinearLayout>

Activity:

public classMYSQLite extendsActivityimplementsView.OnClickListener{

    EditTextword,note,willChange;

    SQLiteDatabasedb;

    ListViewshowWords;

    List<String>listWords;

    Heplpterhelpter;

    ArrayAdapteradapter;

    StringtableName;

    @Override

    protected void onCreate(Bundle savedInstanceState){

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_sqllite);

        tableName="Strings";

        //方法1

//      helpter=newHeplpter(this, "EnglishDB.db", null, 1);//建立資料庫名是englishDB的資料庫版本是1的SQLiteOpenHelpter對象

//      db=helpter.getReadableDatabase();//使用方法1:擷取上面的資料庫,若資料庫不存在則自動建立

        //方法2

        Filedir=Environment.getExternalStorageDirectory();

        Filefile=newFile(dir,"db/EnglishDD.db");

        try {

            file.createNewFile();//先建立資料庫檔案,在擷取資料庫對象

        }catch(IOException e) {

            e.printStackTrace();

        }

        db=SQLiteDatabase.openOrCreateDatabase(file,null);

        db.execSQL("create table if not exists "+tableName+"(id integer primary key,word varchar(255),detailvarchar(255))");//當表不存在時建立表

        ButtoninsertWord=(Button) findViewById(R.id.insertWord);

        ButtondeleteWord=(Button) findViewById(R.id.deleteWord);

        ButtonupdateWord=(Button) findViewById(R.id.updateWord);

        ButtonqueryWord=(Button) findViewById(R.id.queryWord);

        word=(EditText)findViewById(R.id.word);

        note=(EditText) findViewById(R.id.note);

        willChange=(EditText)findViewById(R.id.willChange);

        insertWord.setOnClickListener(this);

        deleteWord.setOnClickListener(this);

        updateWord.setOnClickListener(this);

        queryWord.setOnClickListener(this);

        listWords=new ArrayList<String>();

        showWords=(ListView)findViewById(R.id.showWords);

        adapter=newArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,listWords);

        showWords.setAdapter(adapter);

    }

    @Override

    public void onClick(View arg0) {

        Stringwords=word.getText().toString();

        Stringcontent=note.getText().toString();

        switch(arg0.getId()){

        case R.id.insertWord:

//db.execSQL("insert intotableName(id,word,detail)values(null,"+words+","+content+")");

//db.execSQL("insert intotableName values(null,?,?)",new String[]{words,content});

            ContentValuesvalues=newContentValues();

            values.put("word", words);

            values.put("detail",content);

            db.insert(tableName,"空值", values);//第一個參數是表名,第二個參數values是空值或不包含任何key-values值時有效,第三個參數是插入資料的内容values

            break;

        case R.id.deleteWord:

            db.execSQL("delete from"+tableName+" where word=?",new String[]{words});

//          db.delete(tableName,"word= ?", new String[]{words});//第一個參數是表名,第二個參數是where條件,第三個參數是where條件的參數

            break;

        case R.id.updateWord:

//          db.execSQL("update"+tableName+" setword="+words+",detail="+content+" whereword="+willChange.getText().toString());

            ContentValuesvaluess=newContentValues();

            valuess.put("word", words);

            valuess.put("detail",content);

            db.update(tableName, valuess,"word=?",newString[]{willChange.getText().toString()});//第一個參數是表名,第二個參數是修改成的内容values,第三個參數是where條件,第四個參數是條件的參數集合

            break;

        case R.id.queryWord:

//          db.execSQL("selectword,detail from "+tableName);

            Cursorcursor=db.rawQuery("select * from "+tableName,null);

            listWords.clear();

            while(cursor.moveToNext()){

                listWords.add(cursor.getString(1)+":"+cursor.getString(2));

            }

            adapter.notifyDataSetChanged();

            cursor.close();

            break;

            default:

                break;

        }

    }

    @Override

    protected void onDestroy() {

        super.onDestroy();

//      helpter.close();

        db.close();

    }

}

SQLiteOpenHelpter:

public classHeplpter extendsSQLiteOpenHelper{

    //name是建立的資料庫的名稱字尾是.db,factory是Cursor工廠可以寫null為預設的工廠,vertsion是資料庫的版本

    public Heplpter(Contextcontext, String name, CursorFactory factory,

            int version) {

        super(context, name, factory,version);//使用預設的cursorFactory

    }

    //當調用getWritableDatabase()(以寫的方式打開資料庫,若資料庫的磁盤空間滿了,資料庫則隻能讀不能寫了,此時用本方法打開則會報錯)或getReadablDatabase()(先以讀寫的方式打開資料庫,若資料庫的磁盤空間滿了,此時打開資料庫就會打開失敗,則會以隻讀的方式打開資料庫)方法擷取資料庫對象時調用,若不存在資料庫則系統或自動建立愛一個在調用oncreate(),其中自動建立一個表,用于操作資料

    @Override

    public void onCreate(SQLiteDatabasedb) {

        db.execSQL("create table English(id integer primary keyautoincrement,word varchar(255),detail varchar(255))");//執行sql語句

    }

    //當版本變化時調用,當建立本執行個體對象時會傳入一個version,該version高于之前的版本号則會調用.

    @Override

    public voidonUpgrade(SQLiteDatabase db, int oldVersion,int newVersion) {

        }}