android 之數據庫sqlite 使用

  初步嘗試sqlite 確實比較輕量級,功能強大,支持五種數據類型,NULL、INTEGER、REAL(浮點型)、TEXT(字符文本型),sqlite 最大特點就是可以保存任何類型的數據到任何字段中,而無論這列聲明的數據類型是什麼,如 : 可以在Integer 類型存放字符串,有一種情況除外: 定義爲integer primary key 的字段只能存儲64位整數,如果像其保存整數以外的數據會產生錯誤

    與關係型數據庫相比sqlite 最大限制除了字段無類型外,就是不支持外鍵約束,當然就不支持表連接了

對於sqlite 比較重要的類

SQLiteOpenHelper 他是一個輔助類,用來管理數據庫的創建和數據庫的版本。通過繼承這個類,實現他的一些方法對數據庫進行操作

SQLiteDataBase 代表一個數據庫對象,主要有create() execSQL() 以及 beginTransaction() endTransaction() 

SQLiteCursor 代表查詢結果的記錄集,主要操作MoveFirst() MoveLast() MoveNext() Move()  IsLast() GetColumns() 

    實現增,刪,改,查,代碼如下


main.xml

[html] view plaincopy
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:paddingBottom="@dimen/activity_vertical_margin"  
  6.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  7.     android:paddingRight="@dimen/activity_horizontal_margin"  
  8.     android:paddingTop="@dimen/activity_vertical_margin"  
  9.     tools:context=".MainActivity"  
  10.     android:orientation="vertical" >  
  11.   
  12.     <TextView  
  13.         android:id="@+id/counttip"  
  14.         android:layout_width="wrap_content"  
  15.         android:layout_height="wrap_content"  
  16.         android:text="@string/hello" />  
  17.       
  18.     <ListView   
  19.         android:id="@+id/ListView01"  
  20.         android:layout_width="wrap_content"  
  21.         android:layout_height="wrap_content"></ListView>  
  22.   
  23. </LinearLayout>  

main.java

[java] view plaincopy
  1. package com.example.i18n;  
  2.   
  3. import android.os.Bundle;  
  4. import android.app.Activity;  
  5. import android.content.ContentValues;  
  6. import android.database.Cursor;  
  7. import android.database.sqlite.SQLiteDatabase;  
  8. import android.util.Log;  
  9. import android.widget.ListAdapter;  
  10. import android.widget.ListView;  
  11. import android.widget.SimpleCursorAdapter;  
  12. import android.widget.TextView;  
  13.   
  14. public class MainActivity extends Activity {  
  15.   
  16.     private static final String TAG = MainActivity.class.getSimpleName();  
  17.       
  18.     private ListView lv = null;  
  19.     private TextView tv = null;  
  20.     private SQLiteDatabase mSQLiteDatabase;  
  21.     private static final String DATABASE_NAME = "Test.db";  
  22.     private static final String TABLE_NAME = "table_test";  
  23.     private static final String COLUMN_ID = "_id"// primary key  
  24.     private static final String COLUMN_NAME = "name";  
  25.     private static final String COLUMN_AGE = "age";  
  26.     private static final String CREATE_TABLE = "create table if not exists " + TABLE_NAME + "(" + COLUMN_ID + " integer primary key,"  
  27.                                                         + COLUMN_NAME + " text," + COLUMN_AGE + " integer)";  
  28.       
  29.     @Override  
  30.     protected void onCreate(Bundle savedInstanceState) {  
  31.         super.onCreate(savedInstanceState);  
  32.         setContentView(R.layout.activity_main);  
  33.         lv = (ListView) this.findViewById(R.id.ListView01);  
  34.         tv = (TextView) this.findViewById(R.id.counttip);  
  35.           
  36.         try {  
  37.             mSQLiteDatabase = this.openOrCreateDatabase(DATABASE_NAME, Activity.MODE_PRIVATE, null);  
  38.         } catch (Exception ex) {  
  39.             Log.e(TAG, "打開或者創建數據庫異常" + ex.getMessage());  
  40.         }  
  41.           
  42.         try {  
  43.             mSQLiteDatabase.execSQL(CREATE_TABLE);  
  44.         } catch (Exception ex) {  
  45.             Log.e(TAG, "創建表異常" + ex.getMessage());  
  46.         }  
  47.         insertData();  
  48.         insertData2();  
  49.         this.selectData();  
  50.     }  
  51.   
  52.   
  53.     @Override  
  54.     protected void onPause() {  
  55.         super.onPause();  
  56.         mSQLiteDatabase.close();  
  57.     }  
  58.       
  59.     /** 
  60.      * 插入數據 
  61.      */  
  62.     private void insertData() {  
  63.         try {  
  64.             String sql = "insert into " + TABLE_NAME + "(" + COLUMN_NAME + "," + COLUMN_AGE + ") values('張三',30)";  
  65.             mSQLiteDatabase.execSQL(sql);  
  66.         } catch (Exception e) {  
  67.             Log.e(TAG,"插入數據異常" + e.getMessage());  
  68.         }  
  69.     }  
  70.       
  71.     /** 
  72.      * 插入數據2 
  73.      */  
  74.     private void insertData2() {  
  75.         try {  
  76.             String sql = "insert into " + TABLE_NAME + "(" + COLUMN_NAME + "," + COLUMN_AGE + ") values(?,?)";  
  77.             Object [] ob = new Object[]{"王五",50};  
  78.             mSQLiteDatabase.execSQL(sql,ob);  
  79.         } catch (Exception e) {  
  80.             Log.e(TAG,"插入數據異常" + e.getMessage());  
  81.         }  
  82.     }  
  83.       
  84.     private void addData() {  
  85.         try {  
  86.             ContentValues cv = new ContentValues();  
  87.             cv.put(COLUMN_NAME, "李四");  
  88.             cv.put(COLUMN_AGE, 40);  
  89.             long num = mSQLiteDatabase.insertOrThrow(TABLE_NAME, null, cv);  
  90.             setTitle("num == " + num);  
  91.         } catch (Exception e) {  
  92.             Log.e(TAG,"插入數據異常" + e.getMessage());  
  93.         }  
  94.     }  
  95.       
  96.     /** 
  97.      * 更新數據 
  98.      */  
  99.     private void updateData() {  
  100.         try {  
  101.             String str = "update " + TABLE_NAME + " set " + COLUMN_AGE + "=25 where id=1";  
  102.             mSQLiteDatabase.execSQL(str);  
  103.         } catch (Exception e) {  
  104.             Log.e(TAG,"更新數據異常" + e.getMessage());  
  105.         }  
  106.     }  
  107.     private void updateData2() {  
  108.         try {  
  109.             String str = "update " + TABLE_NAME + " set " + COLUMN_AGE + "=? where id=?";  
  110.             Object[] ob = new Object[]{33,2};  
  111.             mSQLiteDatabase.execSQL(str);  
  112.         } catch (Exception e) {  
  113.             Log.e(TAG,"更新數據異常" + e.getMessage());  
  114.         }  
  115.     }  
  116.     private void updateData3() {  
  117.         try {  
  118.             ContentValues cv = new ContentValues();  
  119.             cv.put(COLUMN_NAME, "李四");  
  120.             cv.put(COLUMN_AGE, 43);  
  121.             long num = mSQLiteDatabase.update(TABLE_NAME, cv ,COLUMN_NAME + "=?",new String[]{"李四"});  
  122.             setTitle("修改行數 num= " + num);  
  123.         } catch (Exception e) {  
  124.             Log.e(TAG,"更新數據異常" + e.getMessage());  
  125.         }  
  126.     }  
  127.       
  128.     /** 
  129.      * 刪除數據 
  130.      */  
  131.     private void deleteData() {  
  132.         try{  
  133.             String sql = "delete from " + TABLE_NAME +  " where _id=3";  
  134.             mSQLiteDatabase.execSQL(sql);  
  135.         } catch(Exception e) {  
  136.             Log.e(TAG,"刪除數據異常" + e.getMessage());  
  137.         }  
  138.     }  
  139.       
  140.     private void deleteData2() {  
  141.         try{  
  142.             String sql = "delete from " + TABLE_NAME +  " where _id=?";  
  143.             mSQLiteDatabase.execSQL(sql,new Object[]{2});  
  144.         } catch(Exception e) {  
  145.             Log.e(TAG,"刪除數據異常" + e.getMessage());  
  146.         }  
  147.     }  
  148.       
  149.     private void deleteData3() {  
  150.         try{  
  151.             int num = mSQLiteDatabase.delete(TABLE_NAME, "_id=1"null);  
  152.             setTitle("刪除行數 num= " + num);  
  153.         } catch(Exception e) {  
  154.             Log.e(TAG,"刪除數據異常" + e.getMessage());  
  155.         }  
  156.     }  
  157.       
  158.     /** 
  159.      * 查詢數據 
  160.      */  
  161.     private void selectData() {  
  162.         try{  
  163.             String sql = "select * from " + TABLE_NAME;  
  164.             Cursor curson = mSQLiteDatabase.rawQuery(sql, null);  
  165.             if(curson !=null) {  
  166.                 ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.list,curson, new String[]{COLUMN_ID,COLUMN_NAME,COLUMN_AGE}, new int[]{R.id.textView1,R.id.textView2,R.id.textView3});  
  167.                 lv.setAdapter(adapter);  
  168.                 tv.setText(Integer.toString(curson.getCount()));  
  169.             }  
  170.         } catch (Exception e) {  
  171.             Log.e(TAG, "查詢數據異常" + e.getMessage());  
  172.         }  
  173.     }  
  174.       
  175.     /** 
  176.      * 刪除表 
  177.      */  
  178.     private void dropTable() {  
  179.         try{  
  180.             String sql = "drop table " + TABLE_NAME;  
  181.             mSQLiteDatabase.execSQL(sql);  
  182.         } catch(Exception e) {  
  183.             Log.e(TAG, "刪除數據異常" + e.getMessage());  
  184.         }  
  185.     }  
  186.       
  187.     /** 
  188.      * 刪除數據庫 
  189.      */  
  190.     private void dropDataBase() {  
  191.         try{  
  192.             deleteDatabase(DATABASE_NAME);  
  193.         } catch (Exception ex) {  
  194.             Log.e(TAG, "刪除數據庫異常 "+ ex.getMessage());  
  195.         }  
  196.     }  
  197. }  

list.xml

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical" >  
  6.       
  7.     <TextView   
  8.         android:id="@+id/textView1"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:text=""/>  
  12.       
  13.     <TextView   
  14.         android:id="@+id/textView2"  
  15.         android:layout_width="wrap_content"  
  16.         android:layout_height="wrap_content"  
  17.         android:text=""/>  
  18.       
  19.     <TextView   
  20.         android:id="@+id/textView3"  
  21.         android:layout_width="wrap_content"  
  22.         android:layout_height="wrap_content"  
  23.         android:text=""/>  
  24.   
  25. </LinearLayout>  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章