Android中SQLite資料庫的簡單使用

來源:互聯網
上載者:User

Android中SQLite資料庫的簡單使用

File file = new File(“hah.txt”);

//只是建立了一個對象file, file指向了hah.txt這個檔案,hah.txt這個檔案可能存在,也可能不存在。如果檔案不存在,則不會被建立。

必須要有檔案輸出資料流對檔案進行了寫的操作,檔案才會被建立。

 

遊標:在訪問資料庫中表結構時,想訪問表中的某一行的時候,資料庫內部有一個快速的定位方式,這個定位方式是通過索引來實現的。遊標相當於數組的指標,通過遊標的上下移動來尋找資料。


在Android中使用SQLite資料庫,需要繼承SQLiteOpenHelper,該類沒有提供預設的建構函式,所以在子類中必須顯示的調用該類的建構函式。

建立資料庫

package com.test.sqllitedemo;

 

import android.content.Context;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

 

public class MyDBOpenHelper extends SQLiteOpenHelper {

//子類建構函式的參數不一定要和父類建構函式的參數一一對應

public MyDBOpenHelper(Context context) {

/**

* @paramcontext 上下文

* @paramname 資料庫檔案的名稱

* @paramfactory 用來建立遊標對象,null就用預設的遊標工廠

* @paramversion 資料庫的版本 號,從1開始。用來更新資料庫。

* 資料庫尾碼名不是固定的,寫為.db只是為了方便查看和識別

*/

super(context, "test.db", null,1);

}

 

@Override

//資料庫第一次建立的時候自動執行

public void onCreate(SQLiteDatabase db) {

}

 

@Override

//資料庫版本更新時自動執行

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

// TODO Auto-generated method stub

}

 

}

建立資料庫

package com.test.sqllitedemo;

 

import android.app.Activity;

import android.os.Bundle;

 

public class MainActivity extends Activity {

 

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

//執行該行代碼,資料庫不會被建立,只是建立了一個資料庫物件

MyDBOpenHelper helper = new MyDBOpenHelper(this);

//建立或者開啟一個資料庫,該資料庫具有讀寫權限,位於data/data/應用程式套件組合名/databases /檔案夾下面

helper.getWritableDatabase();

}

 

}

 

在SQLite中建立表

SQLite中所有資料類型預設儲存都是字串類型的,沒有長度限制的。超過表定義時的資料長度,也不會報錯。

在Android中SQLite會自動建立一張名為android_metadata的表。用於儲存當前的語言環境的。在SQLite中id推薦使用_id。

SQLite的資料庫版本只能增大,不能減小。

package com.test.sqllitedemo;

 

import android.content.Context;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

 

public class MyDBOpenHelper extends SQLiteOpenHelper {

//子類建構函式的參數不一定要和父類建構函式的參數一一對應

public MyDBOpenHelper(Context context) {

/**

* @paramcontext 上下文

* @paramname 資料庫檔案的名稱

* @paramfactory 用來建立遊標對象,null就用預設的遊標工廠

* @paramversion 資料庫的版本 號,從1開始。用來更新資料庫。

* 資料庫尾碼名不是固定的,寫為.db只是為了方便查看和識別

*/

super(context, "test.db", null,1);

}

 

@Override

//資料庫第一次建立的時候自動執行,如果資料庫已經存在,則不會再次調用該方法

/**

* 該方法中建立表結構,初始化資料庫

* @param db 代表的是建立好的資料庫

*/

public void onCreate(SQLiteDatabase db) {

// TODO Auto-generated method stub

//執行SQL語句

db.execSQL("create table info (_id integer primary key autoincrement,name varchar(20),phone varchar(20))");

}

 

@Override

//資料庫版本更新時自動執行,即資料庫版本號碼有變化的時候執行 資料庫的版本只能變大,不能變小

//int oldVersion, int newVersion用來完成跨版本升級資料庫時保持資料

//如果是壟斷性行業,資料是一次有效情況下,可以強制以前資料失效的方式升級,讓使用者重新輸入資料

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

// TODO Auto-generated method stub

db.execSQL("alter table info add money varchar(10)");

}

}

 

EL運算式只能在jsp頁面中使用。

 

資料庫的增刪改查。

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

tools:context="com.test.databaseoper.MainActivity" >

android:onClick="add"

android:layout_width="wrap_content"

android:layout_height="match_parent"

android:text="add" />

android:onClick="update"

android:layout_width="wrap_content"

android:layout_height="match_parent"

android:text="update" />

android:onClick="delete"

android:layout_width="wrap_content"

android:layout_height="match_parent"

android:text="delete" />

android:onClick="query"

android:layout_width="wrap_content"

android:layout_height="match_parent"

android:text="query" />

 

 

 

package com.test.databaseoper;

 

import android.content.Context;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

 

public class MyDBOpenHelper extends SQLiteOpenHelper {

//子類建構函式的參數不一定要和父類建構函式的參數一一對應

public MyDBOpenHelper(Context context) {

/**

* @param context 上下文

* @param name 資料庫檔案的名稱

* @param factory 用來建立遊標對象,null就用預設的遊標工廠

* @param version 資料庫的版本 號,從1開始。用來更新資料庫。

* 資料庫尾碼名不是固定的,寫為.db只是為了方便查看和識別

*/

super(context, "test.db", null,1);

 

}

 

@Override

//資料庫第一次建立的時候自動執行,如果資料庫已經存在,則不會再次調用該方法

/**

* 該方法中建立表結構,初始化資料庫

* @param db 代表的是建立好的資料庫

*/

public void onCreate(SQLiteDatabase db) {

// TODO Auto-generated method stub

//執行SQL語句

db.execSQL("create table info (_id integer primary key autoincrement,name varchar(20),phone varch ar(20))");

}

 

@Override

//資料庫版本更新時自動執行,即資料庫版本號碼有變化的時候執行 資料庫的版本只能變大,不能變小

//int oldVersion, int newVersion用來完成跨版本升級資料庫時保持資料

//如果是壟斷性行業,資料是一次有效情況下,可以強制以前資料失效的方式升級,讓使用者重新輸入資料

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

// TODO Auto-generated method stub

db.execSQL("alter table info add money varchar(10)");

}

 

}

 

 

package com.test.databaseoper;

 

import java.util.Random;

 

import android.app.Activity;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.os.Bundle;

import android.view.View;

 

public class MainActivity extends Activity {

 

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

 

}

 

public void add(View view){

//建立資料庫

MyDBOpenHelper helper = new MyDBOpenHelper(this);

SQLiteDatabase db = helper.getWritableDatabase();

Random random = new Random();

String sql = "insert into info(name,phone)values(?,?)";

//在SQLite中,也可以使用預留位置來傳遞參數

db.execSQL(sql, new Object[]{"lisi"+random.nextInt(100),"453231"});

//釋放資源

db.close();

}

 

public void delete(View view){

 

}

 

public void update(View view){

 

}

 

public void query(View view){

MyDBOpenHelper helper = new MyDBOpenHelper(this);

SQLiteDatabase db = helper.getWritableDatabase();

String sql = "select * from info";

Cursor cursor = db.rawQuery(sql, null);

while (cursor.moveToNext()) {

String id = cursor.getString(0);

String name = cursor.getString(1);

String phone = cursor.getString(2);

System.out.println(id+" "+name+" "+phone);

}

//釋放資源

cursor.close();

db.close();

}

}

 

在SQLite中,所有的資料都是當做字串存的。

Android資料庫中支援中文顯示

 

查看SQLite中表中的資料的三種方式

1.寫sql語句把資料查出,顯示在logcat中查看

2.在應用程式獨立資料區,把資料庫pull出來,然後再可是話工具中查看

3.在命令列查看SQLite資料庫中表中的資料

更改命令列預設的編碼集

chcp(change current page) 65001(utf-8的編碼值)


插入重複資料時,應該提示使用者是否覆蓋已有的資料。

刪除資料時,應該提示使用者是否確定刪除。

 

程式的設計應該有良好的提示和操作方式。

 

查詢操作不會更改資料庫中的內容。一般擷取可讀的資料庫。

多線程寫資料庫,必須明確寫入的先後順序。以及加鎖。

讀的操作可以多線程並行作業,寫資料庫的操作必須枷鎖。

 

googleAndroidapi對資料庫的增刪改查

package com.test.databaseoper;

 

import java.util.Random;

 

import android.app.Activity;

import android.content.ContentValues;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.os.Bundle;

import android.view.View;

import android.widget.Toast;

 

public class GoogleDataBaseOPR extends Activity {

 

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

}

 

public void add(View view) {

// 建立資料庫

MyDBOpenHelper helper = new MyDBOpenHelper(this);

SQLiteDatabase db = helper.getWritableDatabase();

Random random = new Random();

ContentValues values = new ContentValues();

values.put("name", "lisi" + random.nextInt(100));

values.put("phone", "12345678");

 

/*

* db.insert(table, nullColumnHack, values)

* 第一個參數:表名

* 第二個參數:要填充空值的列

* 第三個參數:插入的值 map集合,ContentValues

*/

long id = db.insert("info", null, values);

if (id != -1) {

Toast.makeText(this, "添加成功,添加在" + id + "行", Toast.LENGTH_SHORT)

.show();

} else {

Toast.makeText(this, "添加失敗", Toast.LENGTH_SHORT).show();

}

// 釋放資源

db.close();

}

 

public void delete(View view) {

MyDBOpenHelper helper = new MyDBOpenHelper(this);

SQLiteDatabase db = helper.getWritableDatabase();

/*

* db.delete(table, whereClause, whereArgs)

* 第一個參數:表名

* 第二個參數:選擇條件

* 第三個參數:選擇條件的參數

* 傳回值:刪除的行數,如果沒有刪除,返回0;

*/

int result = db.delete("info", null, null);

db.close();

if (result != 0) {

Toast.makeText(this, "刪除"+ result + "行", Toast.LENGTH_SHORT)

.show();

} else {

Toast.makeText(this, "刪除失敗" , Toast.LENGTH_SHORT).show();

}

}

 

public void update(View view) {

MyDBOpenHelper helper = new MyDBOpenHelper(this);

SQLiteDatabase db = helper.getWritableDatabase();

/*

* db.update(table, values, whereClause, whereArgs)

* 第一個參數:表名

* 第二個參數:插入的值

* 第三個參數:選擇條件,沒有選擇條件時填null

* 第四個參數:選擇條件的參數 沒有參數時填null

* 傳回值:修改的行數,如果沒有修改,返回0;

*/

ContentValues values = new ContentValues();

values.put("name", "lisi");

values.put("phone", "12345678");

int result = db.update("info", values, null, null);

if (result != 0) {

Toast.makeText(this, "修改了第"+ result + "行", Toast.LENGTH_SHORT)

.show();

} else {

Toast.makeText(this, "修改失敗" , Toast.LENGTH_SHORT).show();
}

}

 

public void query(View view) {

MyDBOpenHelper helper = new MyDBOpenHelper(this);

SQLiteDatabase db = helper.getWritableDatabase();

/*

* db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy)

* 第一個參數:表名

* 第二個參數:返回的列 null表示返回所有列

* 第三個參數:選擇條件,沒有選擇條件寫null

* 第四個參數:選擇條件的參數,沒有選擇條件參數寫null

* 第五個參數:分組條件,沒有寫null

* 第六個參數:分組條件,沒有寫null

* 第七個參數:分組條件,沒有寫null

* 傳回值:查詢結果的記錄的條數

*/

//Cursor cursor = db.query("info", null, null, null,null,null,null);

Cursorcursor=db.query("info",newString[]{"_id","name","phone"},null,null,null,null,null);

while (cursor.moveToNext()) {

String id = cursor.getString(0);

String name = cursor.getString(1);

String phone = cursor.getString(2);

System.out.println(id+" "+name+" "+phone);

}

//釋放資源

cursor.close();

db.close();

db.close();

}

}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.