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;
publicclassMyDBOpenHelperextendsSQLiteOpenHelper {
//子類建構函式的引數不一定要和父類建構函式的引數一一對應
publicMyDBOpenHelper(Context context) {
/**
* @paramcontext 上下文
* @paramname 資料庫檔案的名稱
* @paramfactory 用來建立遊標物件,null就用預設的遊標工廠
* @paramversion 資料庫的版本 號,從1開始。用來更新資料庫。
* 資料庫字尾名不是固定的,寫為.db只是為了方便檢視和識別
*/
super(context, "test.db", null,1);
}
@Override
//資料庫第一次建立的時候自動執行
publicvoidonCreate(SQLiteDatabase
}
@Override
//資料庫版本更新時自動執行
publicvoidonUpgrade(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;
publicclassMyDBOpenHelperextendsSQLiteOpenHelper {
//子類建構函式的引數不一定要和父類建構函式的引數一一對應
publicMyDBOpenHelper(Context context) {
/**
* @paramcontext 上下文
* @paramname 資料庫檔案的名稱
* @paramfactory 用來建立遊標物件,null就用預設的遊標工廠
* @paramversion 資料庫的版本 號,從1開始。用來更新資料庫。
* 資料庫字尾名不是固定的,寫為.db只是為了方便檢視和識別
*/
super(context, "test.db", null,1);
}
@Override
//資料庫第一次建立的時候自動執行,如果資料庫已經存在,則不會再次呼叫該方法
/**
* 該方法中建立表結構,初始化資料庫
* @param db 代表的是建立好的資料庫
*/
publicvoidonCreate(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用來完成跨版本升級資料庫時保持資料
//如果是壟斷性行業,資料是一次有效的情況下,可以強制以前資料失效的方式升級,讓使用者重新輸入資料
publicvoidonUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("alter table info add money varchar(10)");
}
}
EL表示式只能在jsp頁面中使用。
資料庫的增刪改查。
<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="com.test.databaseoper.MainActivity" >
<Button
android:onClick="add"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="add" />
<Button
android:onClick="update"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="update" />
<Button
android:onClick="delete"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="delete" />
<Button
android:onClick="query"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="query" />
</LinearLayout>
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();
}
}