本文实例讲述了Android中数据库常见操作。分享给大家供大家参考,具体如下:
android中数据库操作是非常常见了,我们会经常用到,操作的方法也有很多种形式,这里我就把最常见的两种形式记录下来了,以备以后用到方便查看。我就不写注释和解释了,因为android数据库的操作和其它数据库操作本质上都是一样的,大同小异。需要的一些基本解释都在代码中,直接上代码了。
简单的代码文件目录:
首先这个类是数据库帮助类,DBHelper.java,代码如下:
package net.loonggg.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* 数据库帮助类,继承android自带的SQLiteOpenHelper 主要用于数据库的创建与更新
*
* @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);
}
}
其次是数据库信息类,DBInfo.java,代码如下:
package net.loonggg.db;
/**
* 数据库信息类,主要是保存一些数据库的版本,名字,及数据库表的创建语句和表的信息等,通过这个类记录,方便操作
*
* @author loonggg
*
*/
public class DBInfo {
/**
* 数据库信息
*
* @author loonggg
*
*/
public static class DB {
// 数据库名称
public static final String DB_NAME = \"test.db\";
// 数据库的版本号
public static final int DB_VERSION = 1;
}
/**
* 数据库表的信息
*
* @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;
}
}
再次是数据库操作类,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;
/**
* 数据库操作类,这个类主要的功能是:存放数据库操作的一些方法 这里有一些例子:包含数据库的增删改查,分别有两种方法的操作,各有优缺点,都在解释中
*
* @author loonggg
*
*/
public class DBService {
private DBHelper dbHelper = null;
public DBService(Context context) {
dbHelper = new DBHelper(context);
}
/**
* 添加一条记录到数据库
*
* @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();
// 缺点无返回值
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 });// 返回值为受影响的行数,大于0代表成功
db.close();
return result;
}
/**
* 返回所有的数据库信息
*
* @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,简单的调用了一下,这些操作,代码如下:
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对应的布局文件,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=\"查询全部\" /> </LinearLayout>
到这里就介绍完了,这些代码并不高深,之所以记录下来,是留着以后用到的时候方便查看,当然这个代码对于初学者,还是非常有帮助的。
希望本文所述对大家Android程序设计有所帮助。
本文地址:https://www.stayed.cn/item/4843
转载请注明出处。
本站部分内容来源于网络,如侵犯到您的权益,请 联系我