Android中數(shù)據(jù)庫(kù)常見操作實(shí)例分析
本文實(shí)例講述了Android中數(shù)據(jù)庫(kù)常見操作。分享給大家供大家參考,具體如下:
android中數(shù)據(jù)庫(kù)操作是非常常見了,我們會(huì)經(jīng)常用到,操作的方法也有很多種形式,這里我就把最常見的兩種形式記錄下來了,以備以后用到方便查看。我就不寫注釋和解釋了,因?yàn)閍ndroid數(shù)據(jù)庫(kù)的操作和其它數(shù)據(jù)庫(kù)操作本質(zhì)上都是一樣的,大同小異。需要的一些基本解釋都在代碼中,直接上代碼了。
簡(jiǎn)單的代碼文件目錄:


首先這個(gè)類是數(shù)據(jù)庫(kù)幫助類,DBHelper.java,代碼如下:
package net.loonggg.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* 數(shù)據(jù)庫(kù)幫助類,繼承android自帶的SQLiteOpenHelper 主要用于數(shù)據(jù)庫(kù)的創(chuàng)建與更新
*
* @author loonggg
*
*/
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, DBInfo.DB.DB_NAME, null, DBInfo.DB.DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DBInfo.Table.USER_INFO_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DBInfo.Table.USER_INFO_DROP);
onCreate(db);
}
}
其次是數(shù)據(jù)庫(kù)信息類,DBInfo.java,代碼如下:
package net.loonggg.db;
/**
* 數(shù)據(jù)庫(kù)信息類,主要是保存一些數(shù)據(jù)庫(kù)的版本,名字,及數(shù)據(jù)庫(kù)表的創(chuàng)建語(yǔ)句和表的信息等,通過這個(gè)類記錄,方便操作
*
* @author loonggg
*
*/
public class DBInfo {
/**
* 數(shù)據(jù)庫(kù)信息
*
* @author loonggg
*
*/
public static class DB {
// 數(shù)據(jù)庫(kù)名稱
public static final String DB_NAME = "test.db";
// 數(shù)據(jù)庫(kù)的版本號(hào)
public static final int DB_VERSION = 1;
}
/**
* 數(shù)據(jù)庫(kù)表的信息
*
* @author loonggg
*
*/
public static class Table {
public static final String USER_INFO_TB_NAME = "user_table";
public static final String USER_INFO_CREATE = "CREATE TABLE IF NOT EXISTS "
+ USER_INFO_TB_NAME
+ " ( _id INTEGER PRIMARY KEY,userId text,userName text)";
public static final String USER_INFO_DROP = "DROP TABLE"
+ USER_INFO_TB_NAME;
}
}
再次是數(shù)據(jù)庫(kù)操作類,DBService.java,代碼如下:
package net.loonggg.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import net.loonggg.db.DBHelper;
import net.loonggg.db.DBInfo.Table;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
/**
* 數(shù)據(jù)庫(kù)操作類,這個(gè)類主要的功能是:存放數(shù)據(jù)庫(kù)操作的一些方法 這里有一些例子:包含數(shù)據(jù)庫(kù)的增刪改查,分別有兩種方法的操作,各有優(yōu)缺點(diǎn),都在解釋中
*
* @author loonggg
*
*/
public class DBService {
private DBHelper dbHelper = null;
public DBService(Context context) {
dbHelper = new DBHelper(context);
}
/**
* 添加一條記錄到數(shù)據(jù)庫(kù)
*
* @param id
* @param name
*/
public void add(String id, String name) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
// 不好之處:無返回值,無法判斷是否插入成功
db.execSQL("insert into user_table (userId,userName) values (?,?)",
new Object[] { id, name });
db.close();
}
public long addAndroid(String id, String name) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("userId", id);
values.put("userName", name);
// 好處:有返回值
long result = db.insert(Table.USER_INFO_TB_NAME, null, values);// 返回值是插入的是第幾行,大于0代表添加成功
db.close();
return result;
}
/**
* 查詢某條記錄是否存在
*
* @param name
* @return
*/
public boolean find(String name) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.rawQuery(
"select * from user_table where userName = ?",
new String[] { name });
boolean result = cursor.moveToNext();
db.close();
return result;
}
public boolean findAndroid(String name) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.query(Table.USER_INFO_TB_NAME, null, "userName = ?",
new String[] { name }, null, null, null);
boolean result = cursor.moveToNext();// true代表查找到了
db.close();
return result;
}
/**
* 修改一條記錄
*
* @param id
* @param name
*/
public void update(String id, String name) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
// 缺點(diǎn)無返回值
db.execSQL("update user_table set userName = ? where userId = ?",
new Object[] { name, id });
db.close();
}
public int updateAndroid(String id, String name) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("userName", name);
// 返回值大于0代表修改更新成功
int result = db.update(Table.USER_INFO_TB_NAME, values, "userId = ?",
new String[] { id });
db.close();
return result;
}
/**
* 刪除一條記錄
*
* @param name
*/
public void delete(String name) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.execSQL("delete from user_table where userName = ?",
new String[] { name });
db.close();
}
public int deleteAndroid(String name) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
int result = db.delete(Table.USER_INFO_TB_NAME, "userName = ?",
new String[] { name });// 返回值為受影響的行數(shù),大于0代表成功
db.close();
return result;
}
/**
* 返回所有的數(shù)據(jù)庫(kù)信息
*
* @return
*/
public List<HashMap<String, String>> findAll() {
List<HashMap<String, String>> list = null;
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from user_table", null);
if (cursor.getCount() > 0) {
list = new ArrayList<HashMap<String, String>>();
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex("userId"));
String name = cursor.getString(cursor
.getColumnIndex("userName"));
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", id);
map.put("name", name);
list.add(map);
}
}
cursor.close();
db.close();
return list;
}
public List<HashMap<String, String>> findAllAndroid() {
List<HashMap<String, String>> list = null;
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.query(Table.USER_INFO_TB_NAME, new String[] {
"userId", "userName" }, null, null, null, null, null);
if (cursor.getCount() > 0) {
list = new ArrayList<HashMap<String, String>>();
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex("userId"));
String name = cursor.getString(cursor
.getColumnIndex("userName"));
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", id);
map.put("name", name);
list.add(map);
}
}
cursor.close();
db.close();
return list;
}
}
最后是MainActivity,簡(jiǎn)單的調(diào)用了一下,這些操作,代碼如下:
package net.loonggg.test;
import net.loonggg.service.DBService;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private Button queryOne;
private Button insert;
private Button update;
private Button delete;
private Button findAll;
private DBService service;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queryOne = (Button) findViewById(R.id.queryOne);
insert = (Button) findViewById(R.id.insert);
update = (Button) findViewById(R.id.update);
delete = (Button) findViewById(R.id.delete);
findAll = (Button) findViewById(R.id.findAll);
queryOne.setOnClickListener(new ButtonListener());
insert.setOnClickListener(new ButtonListener());
update.setOnClickListener(new ButtonListener());
delete.setOnClickListener(new ButtonListener());
findAll.setOnClickListener(new ButtonListener());
service = new DBService(this);
}
class ButtonListener implements View.OnClickListener {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.queryOne:
// service.find("loonggg");
service.findAndroid("loonggg");
break;
case R.id.insert:
// service.add("1", "loonggg");
service.addAndroid("2", "heihei");
break;
case R.id.update:
// service.update("1", "timmy");
service.updateAndroid("1", "haha");
break;
case R.id.delete:
// service.delete("timmy");
service.deleteAndroid("heihei");
break;
case R.id.findAll:
// service.findAll();
service.findAllAndroid();
break;
default:
break;
}
}
}
}
還有MainActivity對(duì)應(yīng)的布局文件,activity_main.xml:
<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" > <Button android:id="@+id/queryOne" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="查詢一條記錄" /> <Button android:id="@+id/insert" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="添加" /> <Button android:id="@+id/update" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="修改" /> <Button android:id="@+id/delete" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="刪除" /> <Button android:id="@+id/findAll" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="查詢?nèi)? /> </LinearLayout>
到這里就介紹完了,這些代碼并不高深,之所以記錄下來,是留著以后用到的時(shí)候方便查看,當(dāng)然這個(gè)代碼對(duì)于初學(xué)者,還是非常有幫助的。
希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。
- Android SQLite數(shù)據(jù)庫(kù)增刪改查操作的使用詳解
- Android使用SQLite數(shù)據(jù)庫(kù)的簡(jiǎn)單實(shí)例
- Android學(xué)習(xí)筆記-保存數(shù)據(jù)到SQL數(shù)據(jù)庫(kù)中(Saving Data in SQL Databases)
- Android中操作SQLite數(shù)據(jù)庫(kù)快速入門教程
- Android SQLite數(shù)據(jù)庫(kù)增刪改查操作的案例分析
- Android 數(shù)據(jù)庫(kù)打包隨APK發(fā)布的實(shí)例代碼
- android通過jxl讀excel存入sqlite3數(shù)據(jù)庫(kù)
- Android操作SQLite數(shù)據(jù)庫(kù)(增、刪、改、查、分頁(yè)等)及ListView顯示數(shù)據(jù)的方法詳解
- Android通過Webservice操作sqlserver數(shù)據(jù)庫(kù)實(shí)例代碼
- Android開發(fā)中的數(shù)據(jù)庫(kù)事務(wù)用法分析
- Android編程連接MongoDB及增刪改查等基本操作示例
相關(guān)文章
android studio 使用Mocklocation虛擬定位
這篇文章主要介紹了android studio 使用Mocklocation虛擬定位總結(jié),本文分步驟給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-12-12
Android編程之計(jì)時(shí)器Chronometer簡(jiǎn)單示例
這篇文章主要介紹了Android計(jì)時(shí)器Chronometer簡(jiǎn)單用法,結(jié)合實(shí)例形式分析了Android計(jì)時(shí)器Chronometer的定義、事件響應(yīng)及界面布局相關(guān)操作技巧,需要的朋友可以參考下2017-08-08
Android編程之基于Log演示一個(gè)activity生命周期實(shí)例詳解
這篇文章主要介紹了Android編程之基于Log演示一個(gè)activity生命周期,結(jié)合完整實(shí)例形式較為詳細(xì)的分析總結(jié)了Log演示activity生命周期的具體用法及Log的具體使用方法,需要的朋友可以參考下2015-12-12

