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

Android SQLite數(shù)據(jù)庫基本操作方法

 更新時間:2017年02月13日 08:33:36   作者:指點  
本篇文章主要介紹了Android SQLite數(shù)據(jù)庫基本操作方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

程序的最主要的功能在于對數(shù)據(jù)進(jìn)行操作,通過對數(shù)據(jù)進(jìn)行操作來實現(xiàn)某個功能。而數(shù)據(jù)庫就是很重要的一個方面的,Android中內(nèi)置了小巧輕便,功能卻很強(qiáng)的一個數(shù)據(jù)庫–SQLite數(shù)據(jù)庫。那么就來看一下在Android程序中怎么去操作SQLite數(shù)據(jù)庫來實現(xiàn)一些需求的吧,仍然以一個小例子開始:

在創(chuàng)建Android項目之前,我們應(yīng)該想一下我們要定義的數(shù)據(jù)庫的相關(guān)信息和里面的表格的相關(guān)信息,為了日后數(shù)據(jù)庫的更新更加方便 ,我們可以用一個專門的類保存數(shù)據(jù)庫的相關(guān)信息,以后如果要更新數(shù)據(jù)庫的話只需要該動這個類就行了。這樣使得日后的操作更加方便。

新建一個Android工程:

在Src文件夾下新建一個包com.example.databaseHelper:

在這個包中創(chuàng)建兩個類,首先我們來看第一個類DatabaseStatic.Java:

package com.example.databaseHelper;

public class DatabaseStatic {

 public final static String DATABASE_NAME = "BookStore.db";
 public final static int DATABASE_VERSION = 1;

 public final static String TABLE_NAME = "book";
 public final static String BOOK_NAME = "bookName";
 public final static String ID = "_id";
 public final static String AUTHOR = "author";
 public final static String PRICE = "price";
 public final static String DATE = "sellData";
}

這個類中定義了數(shù)據(jù)庫名稱、版本、還有里面有一個名為“book”的表的相關(guān)信息,實現(xiàn)我們上面的意圖,接下來是這個包里面的另外一個類MyHelper.java:

package com.example.databaseHelper;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;

/*
 * 在這個類的構(gòu)造函數(shù)里面我們調(diào)用了父類的構(gòu)造方法用來創(chuàng)建數(shù)據(jù)庫文 
 * 件,第二個構(gòu)造方法只是為了方便構(gòu)造(不用些那么多的參數(shù))
 * 這個類繼承了 SQLiteOpenHelper 類,并且重寫了父類里面的 
onCreate方法和 onUpgrade方法,
 * onCreate方法當(dāng)數(shù)據(jù)庫文件不存在的時候會被調(diào)用來創(chuàng)建一個新的數(shù)
 * 據(jù)庫文件(不懂的小伙伴可以百度一下)
 */

public class MyHelper extends SQLiteOpenHelper{

 public static String CREATE_TABLE = "create table "+ DatabaseStatic.TABLE_NAME +"(" + 
   DatabaseStatic.BOOK_NAME + " varchar(30), " + 
   DatabaseStatic.ID + " Integer primary key autoincrement, " + 
   DatabaseStatic.AUTHOR + " varchar(20) not null, " + 
   DatabaseStatic.PRICE + " real)"; // 用于創(chuàng)建表的SQL語句
 private Context myContext = null;

 public MyHelper(Context context, String name,
   CursorFactory factory, int version) {
  super(context, DatabaseStatic.DATABASE_NAME, null, DatabaseStatic.DATABASE_VERSION);
 }

 public MyHelper(Context context)
 {
  super(context, DatabaseStatic.DATABASE_NAME, null, DatabaseStatic.DATABASE_VERSION);
  myContext = context;
 }

 @Override
 public void onCreate(SQLiteDatabase db) {
  Log.i("UseDatabase", "創(chuàng)建數(shù)據(jù)庫");
  Toast.makeText(myContext, "創(chuàng)建數(shù)據(jù)庫", Toast.LENGTH_SHORT).show();
  db.execSQL(CREATE_TABLE);
 }

 @Override
 public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {

 } 
}

當(dāng)要獲取數(shù)據(jù)庫對象時(通過SQLiteOPenHelper中自帶的方法getWriteableDatabase或者getReadableDatabase),如果數(shù)據(jù)庫文件不存在,這個類里面的onCreate方法會被調(diào)用來創(chuàng)建一個新的數(shù)據(jù)庫文件,如果數(shù)據(jù)庫文件已經(jīng)存在,那么onCreate方法將不會被調(diào)用

activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/mainLayout"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 android:gravity="center_horizontal"
 tools:context=".MainActivity" >

 <Button
  android:id="@+id/buttonCreateDatabase"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="創(chuàng)建數(shù)據(jù)庫" />
 <Button 
  android:id="@+id/buttonInsertDatabase"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="插入數(shù)據(jù)"/>
 <Button 
  android:id="@+id/buttonUpdateDatabase"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="更新數(shù)據(jù)"/>
 <Button 
  android:id="@+id/buttonDeleteDatabase"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="刪除數(shù)據(jù)"/>
 <Button 
  android:id="@+id/buttonQueryDatabase"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="顯示數(shù)據(jù)庫中 Book表中的所有數(shù)據(jù)"/>

</LinearLayout>

一段布局代碼,主要是5個按鈕對應(yīng)5中對數(shù)據(jù)庫的操作:創(chuàng)建數(shù)據(jù)庫、插入數(shù)據(jù)、更新數(shù)據(jù)、刪除數(shù)據(jù)、顯示(查詢)數(shù)據(jù)。
那么最后是MainActivity.java:

import com.example.databaseHelper.DatabaseStatic;
import com.example.databaseHelper.MyHelper;

import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

 private MyHelper myHelper = null;
 private Button button = null;
 private SQLiteDatabase database = null;
 private static int bookSum = 0;
 TextView textView = null;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  textView = new TextView(this);
  LinearLayout layout = (LinearLayout) findViewById(R.id.mainLayout);
  layout.addView(textView);
  button = (Button) findViewById(R.id.buttonCreateDatabase);
  button.setOnClickListener(listener);
  button = (Button) findViewById(R.id.buttonInsertDatabase);
  button.setOnClickListener(listener);
  button = (Button) findViewById(R.id.buttonUpdateDatabase);
  button.setOnClickListener(listener);
  button = (Button) findViewById(R.id.buttonDeleteDatabase);
  button.setOnClickListener(listener);
  button = (Button) findViewById(R.id.buttonQueryDatabase);
  button.setOnClickListener(listener);
 }

 private View.OnClickListener listener = new View.OnClickListener() {

  @Override
  public void onClick(View v) {
   switch(v.getId())
   {
   case R.id.buttonCreateDatabase:
    createDatabase();
    break;
   case R.id.buttonInsertDatabase:
    insertDatabase();
    break;
   case R.id.buttonUpdateDatabase:
    updateDatabase();
    break;
   case R.id.buttonDeleteDatabase:
    deleteDatabase();
    break;
   case R.id.buttonQueryDatabase:
    searchDatabase();
    break;
   }
  }
 };

 private void createDatabase() // 創(chuàng)建或者打開數(shù)據(jù)庫
 {
  myHelper = new MyHelper(this); 

  /*
   * 調(diào)用getWritabelDatabase方法或者
   * getReadableDatabase方法時,如果數(shù)據(jù)庫文
   * 件中不存在(注意一個數(shù)據(jù)庫中可以存在多個表格),
   * 那么會回調(diào)MyHelper類的onCreate方法新建一個數(shù)據(jù)庫文
   * 件并且在這個數(shù)據(jù)庫文件中新建一
   * 個book表格
   */
  myHelper.getWritableDatabase(); 
 }

 private void insertDatabase() // 向數(shù)據(jù)庫中插入新數(shù)據(jù)
 {
  if(myHelper == null)
  {
   myHelper = new MyHelper(this);
  }
  database = myHelper.getWritableDatabase();

  ContentValues cV = new ContentValues();
  cV.put(DatabaseStatic.BOOK_NAME, "C Language");
  cV.put(DatabaseStatic.ID, ++bookSum);
  cV.put(DatabaseStatic.AUTHOR, "zhidian");
  cV.put(DatabaseStatic.PRICE, 42.6);
  /*
   * 這個方法是留給不熟悉SQL語句的小伙伴用的,Android把
   * SQLite的插入語句封裝了起來,
   * 通過 ContentValues 類的對象來保存數(shù)據(jù)庫中的數(shù)據(jù),
   * 于HashMap
   */
  database.insert(DatabaseStatic.TABLE_NAME, null, cV); 

  /*
   * 對應(yīng)的SQL語句:
   * database.execSQL("insert into " + DatabaseStatic.TABLENAME + " values(?, ?, ?, ?)",
   * new Object[]{"C Language", ++bookSum, "zhidian", 42.6});
   * 或者是這個:
   * database.execSQL("insert into " + DatabaseStatic.TABLENAME + "(" + 
   *  DatabaseStatic.BOOKNAME + ", " + DatabaseStatic.ID + ", " + 
   *  DatabaseStatic.AUTHOR + ", " + DatabaseStatic.PRICE + 
   *  ") values(?, ?, ?, ?)", new Object[]{"C Language", ++bookSum, "zhidian", 42.6});
   * 這里將 ? 號理解成一個C語言里面的占位符,然后通過 Object[] 數(shù)組中的內(nèi)容補(bǔ)全,下同
   * 參數(shù)中的 Object[] 數(shù)組是一個通用的數(shù)組,里面的數(shù)據(jù)可以轉(zhuǎn)換為任意類型的數(shù)據(jù),通過這個完成不同數(shù)據(jù)類型變量之間的儲存
  */

  Toast.makeText(this, "插入數(shù)據(jù)成功", Toast.LENGTH_SHORT).show();
 }

 private void updateDatabase() // 更新數(shù)據(jù)
 {
  if(myHelper == null)
  {
   myHelper = new MyHelper(this);
  }
  database = myHelper.getWritableDatabase();

  ContentValues cV = new ContentValues();
  cV.put(DatabaseStatic.AUTHOR, "xiaoming");
  /*
   * 調(diào)用 update 方法,將書名為"C Language" 的書作者更新為 "xiaoming
   */
  database.update(DatabaseStatic.TABLE_NAME, cV, 
    DatabaseStatic.BOOK_NAME + "= ?", new String[]{"C Language"});
  /*
   * 對應(yīng)的SQL語句:
   * database.execSQL("update " + DatabaseStatic.TABLENAME + " set " + DatabaseStatic.AUTHOR + 
   *  "= ? where " + DatabaseStatic.BOOKNAME + " = ?", new String[]{"xiaoming", "C Language"});
   */

  Toast.makeText(this, "數(shù)據(jù)更新成功", Toast.LENGTH_SHORT).show();
 }

 private void deleteDatabase() // 數(shù)據(jù)庫中刪除數(shù)據(jù)
 {
  if(myHelper == null)
  {
   myHelper = new MyHelper(this);
  }
  database = myHelper.getWritableDatabase();

  /*
   * 調(diào)用 delete 方法刪除數(shù)據(jù)庫中的數(shù)據(jù)
   * 對應(yīng)的SQL語句:
   * database.execSQL("delete from " + 
   * DatabaseStatic.TABLE_NAME + " where " + 
   * DatabaseStatic.BOOK_NAME + " = ?", new 
   * String[]{"C Language"});
   */
  database.delete(DatabaseStatic.TABLE_NAME, DatabaseStatic.BOOK_NAME + " = ? ",
    new String[]{"C Language"});

  Toast.makeText(this, "數(shù)據(jù)刪除成功", Toast.LENGTH_SHORT).show();
 }

 private void searchDatabase() // 查詢數(shù)據(jù)庫中的數(shù)據(jù)
 {
  if(myHelper == null)
  {
   myHelper = new MyHelper(this);
  }
  database = myHelper.getWritableDatabase();
  /*
   * 調(diào)用database的query方法,第一個參數(shù)是要查詢的表名,
   * 后面的參數(shù)是一些查詢的約束條件,對應(yīng)于SQL語句的一些參
   * 數(shù), 這里全為null代表查詢表格中所有的數(shù)據(jù)
   * 查詢的結(jié)果返回一個 Cursor對象
   * 對應(yīng)的SQL語句:
   * Cursor cursor = database.rawQuery("select * from book", null);
   */
  Cursor cursor = database.query(DatabaseStatic.TABLE_NAME, null, null, null, null, null, null);

  StringBuilder str = new StringBuilder();
  if(cursor.moveToFirst()) // 顯示數(shù)據(jù)庫的內(nèi)容
  {
   for(; !cursor.isAfterLast(); cursor.moveToNext()) // 獲取查詢游標(biāo)中的數(shù)據(jù)
   {
    str.append(cursor.getString(cursor.getColumnIndex(DatabaseStatic.ID)) + " ");
    str.append(cursor.getString(cursor.getColumnIndex(DatabaseStatic.BOOK_NAME)) + " ");
    str.append(cursor.getString(cursor.getColumnIndex(DatabaseStatic.AUTHOR)) + " ");
    str.append(cursor.getString(cursor.getColumnIndex(DatabaseStatic.PRICE)) + "\n");
   }
  }
  cursor.close(); // 記得關(guān)閉游標(biāo)對象
  if(str.toString().equals(""))
  {
   str.append("數(shù)據(jù)庫為空!");
   textView.setTextColor(Color.RED);
  }
  else 
  {
   textView.setTextColor(Color.BLACK);
  }
  textView.setText(str.toString());
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }
}

MainActivity.java里面主要是實現(xiàn)了5個按鈕對應(yīng)的操作

SQLiteDatabase 類里面提供了對數(shù)據(jù)庫表格進(jìn)行插入、更新、刪除、查詢 的對應(yīng)API,用于給對SQL語句不熟悉的開發(fā)者使用,當(dāng)然我們還可以調(diào)用這個類里面的 execSQL 方法來直接執(zhí)行SQL語句中的插入、更改、刪除操作,用rawQuery 方法來執(zhí)行SQL語句的查詢語句。

Ok,整個工程的項目視圖(可能有些多余。。。):

這里寫圖片描述

好了,運行一下:

這里寫圖片描述 

先點擊“創(chuàng)建數(shù)據(jù)庫”按鈕:

程序中的數(shù)據(jù)庫文件都儲存在 /data/data/<包名>/databases文件中

運行cmd(windows系統(tǒng))運行abd調(diào)試工具(如果沒有將adb.exe加入環(huán)境變量中則需要寫出adb.exe的完整路徑)

輸入 adb shell

再輸入 cd /data/data/com.example.UseDataBase/databases進(jìn)入對應(yīng)儲存文件目錄

再輸入 ls 顯示文件中的子文件目錄,接下來我們就可以對數(shù)據(jù)庫文件進(jìn)行操作了:

輸入 sqlite3 數(shù)據(jù)庫名稱, 就可以對數(shù)據(jù)庫進(jìn)行操作了:

輸入 .table 來查看當(dāng)前數(shù)據(jù)庫文件中的表格目錄, 結(jié)果如下:

這里寫圖片描述 

我們可以看到我們要創(chuàng)建的表格確實存在,證明我們的代碼確實創(chuàng)建了數(shù)據(jù)庫文件和里面對應(yīng)的表。

而我們注意到這里面還有另外一個android_metadata表,這個表是每個數(shù)據(jù)庫文件都會自動生成的,不需要管。

接下來單擊“插入數(shù)據(jù)”按鈕:

之后 在控制臺中輸入 “select * from book;”,這個是查詢數(shù)據(jù)庫文件中的數(shù)據(jù)的SQL語句,不熟悉的小伙伴可以在網(wǎng)上查到一些教程

這里寫圖片描述 

我們可以看到我們確實在book這張表中成功的插入了一條新的數(shù)據(jù)。

接下來單擊“更新數(shù)據(jù)”按鈕:

這里寫圖片描述 

Ok,確實把書名為“C Language”的書的作者改為了 “xiaowei”,繼續(xù)單擊“刪除”按鈕:

這里寫圖片描述 

使用 “select * from”語句查詢表中的所有數(shù)據(jù),并沒有看到有數(shù)據(jù),我們再單擊一下“顯示數(shù)據(jù)庫中book表中的所有數(shù)據(jù)”按鈕:

這里寫圖片描述 

這樣看來,數(shù)據(jù)庫中book表中的數(shù)據(jù)確實已經(jīng)被我們刪除了。

這里提一下SQLite數(shù)據(jù)庫操作的時候主要用到的數(shù)據(jù)類型:
整形:Integer、字符數(shù)組:varchar(10)、浮點數(shù):real、字符串文本:text。當(dāng)然SQLite還有很多的操作和支持的數(shù)據(jù)類型。

最后給出一些常用的SQL語句:

1、創(chuàng)建數(shù)據(jù)庫表:

create table 表名(參數(shù)1 數(shù)據(jù)類型 約數(shù)條件, 參數(shù)2 數(shù)據(jù)類型 約束條件…) 

例:

復(fù)制代碼 代碼如下:

create table person(_id Integer primary key autoincrement, name varchar(20), sex varchar(5) not null, age Integer)

2、插入數(shù)據(jù):

insert into 表名(參數(shù)1, 參數(shù)2…) values(參數(shù)1的值, 參數(shù)2的值…) 

或者:

insert into 表名 values(參數(shù)1的值, 參數(shù)2的值) 

例:

insert into person(_id, name, sex, age) values(1, “指點”, “男”, 19) 
insert into person values(1, “指點”, “男”, 19)

3、更新數(shù)據(jù):

update 表名 set 參數(shù)1 = 值, 參數(shù)2 = 值… where 條件1 and 條件2 or 條件3… 

更新符合條件的所有數(shù)據(jù)

where后面的條件用 “and” 或者 “or”連接

例:

復(fù)制代碼 代碼如下:

update person set _id = 0, age = 18 where _id = 1 and age<>19 // “<>”符號代表“不等于”

4、刪除數(shù)據(jù):

delete from 表名 where 條件1 and 條件2 or 條件3… 

刪除符合條件的所有數(shù)據(jù)

例:

delete from person where _id > 0 and name = “指點”

前四個操作的SQL語句可用 execSQL 方法帶入?yún)?shù)執(zhí)行

5、查詢數(shù)據(jù):

select 參數(shù)1, 參數(shù)2… from 表名 where 條件1 and 條件2… 

返回的是符合條件的所有的數(shù)據(jù)中的參數(shù)1、參數(shù)2…

例:

select _id, name, sex from person where name = “指點” or _id = 1 

返回的是: 1、“指點”、“男”

注意查詢操作的SQL語句要用 rawQuery方法執(zhí)行,詳見代碼

Ok, 終于把SQLite 的基礎(chǔ)操作總結(jié)完了。這里所說的只是SQLite操作的冰山一角,日后還得多多學(xué)習(xí)。

相關(guān)文章

最新評論