Android 中 SQLite 的應用總結


通過一個demo程序測試了SQLite的語句應用。裏面涉及到,數據庫建立,表的建立,表中數據的添加,更改,刪除,查詢
1. 數據庫的建立
    Android中集成了SQLite數據庫,但是不回自動提供數據庫,所以我們想應用的話第一步是建立自己的數據庫。
    首先引入包   import android.database.sqlite.SQLiteDatabase;
    下面一句話初始化數據庫,也就是建立自己命名的數據句 
    db = openOrCreateDatabase(dbName,MODE_PRIVATE,null);
2. 建立表
    執行語句是
    db.execSQL("CREATE TABLE IF NOT EXISTS mytable(id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar(30), score INTEGER);");
    此語句是通過調用SQLiteDatabase的execSQL()方法,在裏面書寫SQL語句完成的。
3. 數據的添加、更改、刪除
    添加
    db.execSQL("INSERT INTO mytable VALUES('61', 'zhang', '5');");
     更改              
    db.execSQL("UPDATE mytable SET name='pei' WHERE id='61';");
     刪除             
     db.execSQL("DELETE FROM mytable WHERE id='61';");
4. 數據的查詢
    查詢可以通過Android的query方法,此方法會返回一個Cursor對象,通過對Cursor對象的各種操作,可以獲得所需數據。
    獲取對象方法
     Cursor cursor = db.query(tableName,null,null,null,null,null,null);//後面這一堆參數可缺省
    具體實現在下面JAVA代碼的90-108行
5. 代碼
    .XML

點擊(此處)摺疊或打開

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2.     xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
  3.     android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
  4.     android:paddingRight="@dimen/activity_horizontal_margin"
  5.     android:paddingTop="@dimen/activity_vertical_margin"
  6.     android:paddingBottom="@dimen/activity_vertical_margin"
  7.     android:background="@drawable/b2"
  8.     tools:context=".MainActivity">
  9.     //title
  10.     <TextView android:text="Hello SQLite!!"
  11.         android:layout_width="wrap_content"
  12.         android:layout_height="wrap_content"
  13.         android:id="@+id/titleTextView"/>
  14.     //create SQLite
  15.     <Button
  16.         android:text="創建數據庫"
  17.         android:layout_width="wrap_content"
  18.         android:layout_height="wrap_content"
  19.         android:id="@+id/initSQL"
  20.         android:layout_below="@+id/titleTextView"
  21.         android:layout_marginTop="20dp"
  22.         android:layout_alignLeft="@+id/titleTextView"
  23.         />
  24.     //create table
  25.     <Button
  26.         android:layout_width="wrap_content"
  27.         android:layout_height="wrap_content"
  28.         android:text="創建表"
  29.         android:id="@+id/createTable"
  30.         android:layout_below="@+id/initSQL"
  31.         android:layout_marginTop="20dp"
  32.         android:layout_alignLeft="@+id/titleTextView"
  33.         />

  34.     //Android modification data
  35.     <Button
  36.         android:layout_width="wrap_content"
  37.         android:layout_height="wrap_content"
  38.         android:text="Android修改數據"
  39.         android:id="@+id/AndroidModData"
  40.         android:layout_below="@+id/createTable"
  41.         android:layout_marginTop="20dp"
  42.         android:layout_alignLeft="@+id/titleTextView"
  43.         />

  44.     //query data
  45.     <Button
  46.         android:layout_width="wrap_content"
  47.         android:layout_height="wrap_content"
  48.         android:text="查詢數據"
  49.         android:id="@+id/queryData"
  50.         android:layout_below="@+id/AndroidModData"
  51.         android:layout_marginTop="20dp"
  52.         android:layout_alignLeft="@+id/initSQL"
  53.         />

  54.     //SQL modification data
  55.     <Button
  56.         android:layout_width="wrap_content"
  57.         android:layout_height="wrap_content"
  58.         android:text="SQL 修改數據"
  59.         android:id="@+id/SQLModData"
  60.         android:layout_below="@+id/queryData"
  61.         android:layout_marginTop="20dp"
  62.         android:layout_alignLeft="@+id/initSQL"
  63.         />

  64. </RelativeLayout>
    .JAVA

點擊(此處)摺疊或打開

  1. package com.example.warrior.sqliteoperator;

  2. import android.app.Activity;
  3. import android.app.AlertDialog;
  4. import android.content.DialogInterface;
  5. import android.database.Cursor;
  6. import android.database.sqlite.SQLiteDatabase;
  7. import android.support.v7.app.ActionBarActivity;
  8. import android.os.Bundle;
  9. import android.view.Menu;
  10. import android.view.MenuItem;
  11. import android.view.View;
  12. import android.widget.Button;
  13. import android.widget.Toast;


  14. public class MainActivity extends Activity {

  15.     private Button initButton;
  16.     private Button tableButton;
  17.     private Button btn_SqlMod;
  18.     private Button btn_AndroidMod;
  19.     private Button btn_Query;
  20.     private final String dbName = "SQLdb";
  21.     private final String tableName = "mytable";
  22.     private SQLiteDatabase db = null;
  23.     private int i = 1;
  24.     @Override
  25.     protected void onCreate(Bundle savedInstanceState) {
  26.         super.onCreate(savedInstanceState);
  27.         setContentView(R.layout.activity_main);
  28.         initButton = (Button)findViewById(R.id.initSQL);
  29.         initButton.setOnClickListener(new View.OnClickListener() {
  30.             @Override
  31.             public void onClick(View v) {
  32.                 db = openOrCreateDatabase(dbName,MODE_PRIVATE,null);
  33.                 Toast.makeText(getApplicationContext(),"create SQLite Success!!", 1000).show();
  34.             }
  35.         });

  36.         //create table
  37.         tableButton = (Button)findViewById(R.id.createTable);
  38.         tableButton.setOnClickListener(new View.OnClickListener() {
  39.             @Override
  40.             public void onClick(View v) {
  41.                 if(db != null){
  42.                     db.execSQL("CREATE TABLE IF NOT EXISTS mytable(id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar(30), score INTEGER);");
  43.                     Toast.makeText(getApplicationContext(),"create table success!!", 1000).show();
  44.                 }else {
  45.                     Toast.makeText(getApplicationContext(),"None SQL", 1000).show();
  46.                 }
  47.             }
  48.         });

  49.         //sql modification data
  50.         btn_SqlMod = (Button)findViewById(R.id.SQLModData);
  51.         btn_SqlMod.setOnClickListener(new View.OnClickListener() {
  52.             @Override
  53.             public void onClick(View v) {
  54.                 if(db != null){
  55.                     db.execSQL("INSERT INTO mytable VALUES('61', 'zhang', '5');");
  56.                     Toast.makeText(getApplicationContext(),"ADD SUCCESS!!",1000).show();
  57.                     db.execSQL("UPDATE mytable SET name='pei' WHERE id='61';");
  58.                     Toast.makeText(getApplicationContext(), "UPDATE SUCCESS!!", 1000).show();
  59.                     db.execSQL("DELETE FROM mytable WHERE id='61';");
  60.                     Toast.makeText(getApplicationContext(), "DELETE SUCCESS!!", 1000).show();
  61.                 }else {
  62.                     Toast.makeText(getApplicationContext(), "NO SQL", 2000).show();
  63.                 }
  64.             }
  65.         });


  66.         btn_Query = (Button)findViewById(R.id.queryData);
  67.         btn_Query.setOnClickListener(new View.OnClickListener() {
  68.             @Override
  69.             public void onClick(View v) {
  70.                 if(db != null){
  71.                     queryData();
  72.                     Toast.makeText(getApplicationContext(), "SELECT SUCCESS!!", 2000).show();
  73.                 }else {
  74.                     Toast.makeText(getApplicationContext(), "NO SQL", 2000).show();
  75.                 }
  76.             }
  77.         });


  78.     }

  79.     public void queryData(){
  80.         Cursor cursor = db.query(tableName,null,null,null,null,null,null);
  81.         String str = "";
  82.         if(cursor.getCount() != 0){
  83.             cursor.moveToFirst();//跳到第一個遊標
  84.             for(int i=0;i<cursor.getCount();i= i+1){
  85.                 str = str + cursor.getString(0)+""+cursor.getString(1)+""+cursor.getString(2)+"\n";
  86.                 cursor.moveToNext();//下一個遊標
  87.             }
  88.         }
  89.         new AlertDialog.Builder(MainActivity.this).setTitle("query message!!")
  90.                 .setMessage(str)
  91.                 .setNegativeButton("yes", new DialogInterface.OnClickListener() {
  92.                     @Override
  93.                     public void onClick(DialogInterface dialog, int which) {

  94.                     }
  95.                 }).show();
  96.     }


  97.     @Override
  98.     public boolean onCreateOptionsMenu(Menu menu) {
  99.         // Inflate the menu; this adds items to the action bar if it is present.
  100.         getMenuInflater().inflate(R.menu.menu_main, menu);
  101.         return true;
  102.     }

  103.     @Override
  104.     public boolean onOptionsItemSelected(MenuItem item) {
  105.         // Handle action bar item clicks here. The action bar will
  106.         // automatically handle clicks on the Home/Up button, so long
  107.         // as you specify a parent activity in AndroidManifest.xml.
  108.         int id = item.getItemId();

  109.         //noinspection SimplifiableIfStatement
  110.         if (id == R.id.action_settings) {
  111.             return true;
  112.         }

  113.         return super.onOptionsItemSelected(item);
  114.     }
  115. }



                        de

發佈了68 篇原創文章 · 獲贊 10 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章