欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

實(shí)例講解Android App使用自帶的SQLite數(shù)據(jù)庫的基本方法

 更新時(shí)間:2016年04月19日 17:45:18   作者:summerpxy  
這篇文章主要介紹了Android App使用自帶的SQLite數(shù)據(jù)庫的基本方法,SQLite是一個(gè)小巧的內(nèi)嵌型數(shù)據(jù)庫,在數(shù)據(jù)庫需求不大的情況下使用SQLite其實(shí)非常有效,需要的朋友可以參考下

SQLite數(shù)據(jù)庫是android系統(tǒng)內(nèi)嵌的數(shù)據(jù)庫,小巧強(qiáng)大,能夠滿足大多數(shù)SQL語句的處理工作,而SQLite數(shù)據(jù)庫僅僅是個(gè)文件而已。雖然SQLite的有點(diǎn)很多,但并不是如同PC端的mysql般強(qiáng)大,而且android系統(tǒng)中不允許通過JDBC操作遠(yuǎn)程數(shù)據(jù)庫,所以只能通過webservice等手段于php、servlet交互獲取數(shù)據(jù)。

基礎(chǔ)
SQLiteDatabase類,代表了一個(gè)數(shù)據(jù)庫對(duì)象,通過SQLiteDatabase來操作管理數(shù)據(jù)庫。

一些基本的用法:

  •   static  SQLiteDatabase openDatabase(String path,SQLiteDatabase.CUrsorFactory factory,int flag);
  •   static SQLiteDatabase openOrCreateDatabase(File file,SQLiteDatabase.CursorFactory factory);
  •   static SQLiteDatabase openOrCreateDatabase(String path,SQLiteDatabse.CursorFactory factory);

通過這些靜態(tài)方法可以很方便的打開和新建一個(gè)數(shù)據(jù)庫。

  •  execSQL(String sql,Object[] bindArgs)
  • execSQL(String sql)
  • rawQuery(String sql,String[] selectionArgs);
  • beginTransaction()
  • endTransaction()

這些函數(shù)可以完成SQL功能,對(duì)于查詢出來的結(jié)果是用Cursor表示的,類似于JDBC中的ResultSet類,在這些類中通過方法move(int offset)、moveToFirst()、moveToLast()、moveToNext()、moveToPosition(int position)、moveToPrivious()獲取需要的結(jié)果行。

下面通過一個(gè)實(shí)例來說明一下SQLiteDatabase的基本使用:

main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  tools:context=".Main" >
 
  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >
 
    <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:gravity="center"
      android:text="key" />
 
    <EditText
      android:id="@+id/keys"
      android:layout_width="100sp"
      android:layout_height="wrap_content" />
 
    <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:gravity="center"
      android:text="value" />
 
    <EditText
      android:id="@+id/values"
      android:layout_width="100sp"
      android:layout_height="wrap_content" />
 
    <Button
      android:id="@+id/btn"
      android:layout_width="100sp"
      android:layout_height="wrap_content"
      android:text="submit" />
  </LinearLayout>
 
  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
 
    <ListView
      android:id="@+id/lv"
      android:layout_width="match_parent"
      android:layout_height="wrap_content" />
  </LinearLayout>
 
</LinearLayout>

用于填充數(shù)據(jù)的mytextview.xml:

<?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="wrap_content"
  android:orientation="horizontal" >
 
  <TextView
    android:id="@+id/listkey"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="left" />
 
  <TextView
    android:id="@+id/listvalue"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="300sp" />
 
</LinearLayout>

Main.java

package com.app.main;
 
import android.annotation.SuppressLint;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
 
public class Main extends Activity {
 
  EditText ed1 = null;
  EditText ed2 = null;
  Button btn = null;
  ListView lv = null;
  SQLiteDatabase db = null;
 
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
 
    ed1 = (EditText) this.findViewById(R.id.keys);
    ed2 = (EditText) this.findViewById(R.id.values);
    btn = (Button) this.findViewById(R.id.btn);
    lv = (ListView) this.findViewById(R.id.lv);
 
    db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString()
        + "/my.db3", null);
 
    btn.setOnClickListener(new OnClickListener() {
 
      @Override
      public void onClick(View view) {
 
        String key = ed1.getText().toString();
 
        String value = ed2.getText().toString();
 
        try {
          insertData(db, key, value);
 
          Cursor cursor = db.rawQuery("select * from tb_info", null);
 
          inflateListView(cursor);
 
        } catch (Exception e) {
 
          String sql = "create table tb_info(_id integer primary key autoincrement,db_key varchar(20),db_value varchar(50))";
 
          db.execSQL(sql);
 
          insertData(db, key, value);
 
          Cursor cursor = db.rawQuery("select * from tb_info", null);
 
          inflateListView(cursor);
        }
 
      }
 
    });
 
  }
 
  // 向數(shù)據(jù)庫中插入數(shù)據(jù)
  private void insertData(SQLiteDatabase db, String key, String value) {
    db.execSQL("insert into tb_info values (null,?,?)", new String[] { key,
        value });
    System.out.println("------------------");
  }
 
  // 向ListView中填充數(shù)據(jù)
  @SuppressLint("NewApi")
  public void inflateListView(Cursor cursor) {
 
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(Main.this,
        R.layout.mytextview, cursor, new String[] { "db_key",
            "db_value" },
        new int[] { R.id.listkey, R.id.listvalue },
        CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
 
    lv.setAdapter(adapter);
 
  }
 
  @Override
  protected void onDestroy() {
 
    super.onDestroy();
    if (db != null && db.isOpen()) {
      db.close();
    }
  }
 
}

實(shí)現(xiàn)的效果:

2016419174304714.png (720×1280)

需要特別指出,在用SimpleCursorAdapter封裝Cursor的時(shí)候,要求底層數(shù)據(jù)庫表的主鍵列的列名為_id,因?yàn)镾impleCursorAdapter只能識(shí)別主鍵列名為_id的表。

進(jìn)階
   直接使用SQLiteDatabase的openOrCreateDatabase可以直接打開或者是新建一個(gè)SQLiteDatabase,但是這里存在一個(gè)缺點(diǎn)。在每次執(zhí)行SQL語句的時(shí)候都需要在try catch語句中進(jìn)行,如果在try中直接操作的數(shù)據(jù)庫或者表不存在,就需要在catch中重新創(chuàng)建表并且執(zhí)行CRUD操作,并且有關(guān)數(shù)據(jù)庫的每一個(gè)方法都要這么做,重復(fù)的代碼太多了,所以實(shí)際的開發(fā)中大都選用SQLiteOpenHelper類。

主要方法:

  •    synchronized SQLiteDatabase getReadableDatabase():以讀寫的方式打開數(shù)據(jù)庫。
  •    synchronized SQLiteDatabase getWritableDatabase();以寫的方式打開數(shù)據(jù)庫。
  •    abstract void onCreate(SQLiteDatabase db)    當(dāng)?shù)谝淮蝿?chuàng)建數(shù)據(jù)庫的時(shí)候回調(diào)該方法。
  •    abstract void onUprade(SQLiteDatabase db,int oldversion,int newVersion) 數(shù)據(jù)庫版本更新的時(shí)候回調(diào)該方法。
  •   abstract void close()  關(guān)閉所有打開的SQLiteDatabase.


使用方法:

  1)繼承SQLiteOpenHelper。在構(gòu)造方法中的參數(shù)String name就是數(shù)據(jù)庫的名稱。

  2)重寫onCreate和onUpgrade方法。

MySQLiteOpenHelper類:

package com.app.db;
 
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
 
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
 
  String createSQL = "create table tb_test(_id integer primary key autoincrement ,name,age )";
 
  public MySQLiteOpenHelper(Context context, String name,
      CursorFactory factory, int version) {
 
    super(context, name, factory, version);
  }
 
  @Override
  public void onCreate(SQLiteDatabase db) {
 
    db.execSQL(createSQL);
 
  }
 
  @Override
  public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
 
  }
 
}

Main.java

package com.app.main;
 
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Toast;
 
import com.app.db.MySQLiteOpenHelper;
 
public class Main extends Activity {
 
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
 
    MySQLiteOpenHelper helper = new MySQLiteOpenHelper(this, "my.db3",
        null, 1);
 
    String insertSQL = "insert into tb_test values(null,'wx',18)";
 
    SQLiteDatabase db = helper.getReadableDatabase();
 
    db.execSQL(insertSQL);
 
    Cursor cursor = db.rawQuery("select * from tb_test", null);
 
    cursor.moveToFirst();
 
    int id = cursor.getInt(0);
 
    Toast.makeText(this, id+"",Toast.LENGTH_SHORT).show();
  }
 
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
 
    getMenuInflater().inflate(R.menu.main, menu);
     
    return true;
  }
 
}

實(shí)現(xiàn)效果:

2016419174411822.png (720×1280)

相關(guān)文章

  • 詳解Android啟動(dòng)第一幀

    詳解Android啟動(dòng)第一幀

    這篇文章我們就來介紹Android啟動(dòng)第一幀,至于Android第一幀什么時(shí)候開始調(diào)度,具體內(nèi)容我們就來看下面文章內(nèi)容吧,感興趣得小伙伴可以和小編一起來學(xué)習(xí)奧
    2021-10-10
  • Android基于AdapterViewFlipper實(shí)現(xiàn)的圖片/文字輪播動(dòng)畫控件

    Android基于AdapterViewFlipper實(shí)現(xiàn)的圖片/文字輪播動(dòng)畫控件

    這篇文章主要介紹了Android基于AdapterViewFlipper實(shí)現(xiàn)的圖片/文字輪播動(dòng)畫控件,幫助大家更好的理解和學(xué)習(xí)使用Android開發(fā),感興趣的朋友可以了解下
    2021-04-04
  • Android 五大布局方式詳解

    Android 五大布局方式詳解

    本文主要介紹Android 五大布局的知識(shí)資料,這里整理了詳細(xì)的布局資料及實(shí)現(xiàn)示例代碼,和實(shí)現(xiàn)效果圖,有興趣的小伙伴可以參考下
    2016-09-09
  • Android之高效加載大圖的方法示例

    Android之高效加載大圖的方法示例

    這篇文章主要介紹了Android之高效加載大圖的方法示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2019-03-03
  • Android 編程下的計(jì)時(shí)器代碼

    Android 編程下的計(jì)時(shí)器代碼

    在安卓 APP 的手機(jī)號(hào)注冊(cè)邏輯中,經(jīng)常會(huì)有將激活碼發(fā)送到手機(jī)的環(huán)節(jié),這個(gè)環(huán)節(jié)中絕大多數(shù)的應(yīng)用考慮到網(wǎng)絡(luò)延遲或服務(wù)器壓力以及短信服務(wù)商的延遲等原因,會(huì)給用戶提供一個(gè)重新獲取激活碼的按鈕
    2013-08-08
  • Android?Flutter實(shí)現(xiàn)創(chuàng)意時(shí)鐘的示例代碼

    Android?Flutter實(shí)現(xiàn)創(chuàng)意時(shí)鐘的示例代碼

    時(shí)鐘這個(gè)東西很奇妙,總能當(dāng)做創(chuàng)意實(shí)現(xiàn)的入口。這篇文章主要介紹了如何通過Android?Flutter實(shí)現(xiàn)一個(gè)創(chuàng)意時(shí)鐘,感興趣的小伙伴可以了解一下
    2023-03-03
  • android實(shí)現(xiàn)可拖動(dòng)的浮動(dòng)view

    android實(shí)現(xiàn)可拖動(dòng)的浮動(dòng)view

    這篇文章主要為大家詳細(xì)介紹了android實(shí)現(xiàn)可拖動(dòng)的浮動(dòng)view,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-04-04
  • Android應(yīng)用開發(fā)中模擬按下HOME鍵的效果(實(shí)現(xiàn)代碼)

    Android應(yīng)用開發(fā)中模擬按下HOME鍵的效果(實(shí)現(xiàn)代碼)

    Android應(yīng)用開發(fā)中, 有一種場(chǎng)景,就是我們不希望用戶直接按Back鍵退出Activity,而是希望應(yīng)用隱藏到后臺(tái),類似于按Home鍵的效果
    2013-05-05
  • Android 圖片處理縮放功能

    Android 圖片處理縮放功能

    這篇文章主要介紹了Android 圖片處理縮放功能,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2018-06-06
  • Flutter 實(shí)現(xiàn)虎牙/斗魚 彈幕功能

    Flutter 實(shí)現(xiàn)虎牙/斗魚 彈幕功能

    這篇文章主要介紹了Flutter 實(shí)現(xiàn)虎牙/斗魚 彈幕功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-04-04

最新評(píng)論