安卓平台使用sqlite

sqlite也可以算跨平台的小型数据库了,在安卓上使用,和在其他平台上也没有什么区别。

安卓提供了一个抽象类SQLiteOpenHelper来辅助操作sqlite,直接使用SQLiteDatabase也可以操作sqlite数据库。

因为在j2ee中习惯性简单的包装一个jdbc操作数据库,这里也使用SQLiteOpenHelper类简单包装使用一下sqlite,只是一个基础雏形。


package com.example.org.suju.work9;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class MySQliteHandler extends SQLiteOpenHelper {

	private final static int VERSION = 1;
	private SQLiteDatabase db;
	
	public MySQliteHandler(Context context, String name, CursorFactory factory) {
		super(context, name, factory, VERSION);
	}
	
	public MySQliteHandler(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
	}
	
	@Override
	public void onCreate(SQLiteDatabase db) {
		System.out.println("debug:create db");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		System.out.println("debug:upgrade");
	}
	
	/*
	 * @param    name 符合javabean规范的类的方法名
	 * @return   返回getXXX形式无参数方法名
	 */
	private String getMethodName(String name)
	{
		StringBuilder sb = new StringBuilder(name);
		//替换首字符为大写
		char first = sb.charAt(0);
		sb.setCharAt(0, Character.toUpperCase(first));
		sb.insert(0, "get");
		return sb.toString();
	}
	
	/*
	 * 此方法待合并
	 * @param    name 符合javabean规范的类的方法名
	 * @return   返回getXXX形式无参数方法名
	 */
	private String setMethodName(String name)
	{
		StringBuilder sb = new StringBuilder(name);
		//替换首字符为大写
		char first = sb.charAt(0);
		sb.setCharAt(0, Character.toUpperCase(first));
		sb.insert(0, "set");
		return sb.toString();
	}
	
	/*
	 * 根据指定参数调用合适的ContentValues的put方法
	 */
	private ContentValues contentPutValue(ContentValues cv, String key, Object value) throws Exception
	{
		Method method = ContentValues.class.getMethod("put", String.class, value.getClass());
		method.invoke(cv, key, value);
		return cv;
	}
	
	public void insert(String table, Object obj)
	{
		db = getWritableDatabase();
		Class<?> cls = obj.getClass();
		Field[] fields = cls.getDeclaredFields();
		ContentValues cv = new ContentValues();
		
		for (Field f: fields) {
			String mname = getMethodName(f.getName());
			try {
				//根据bean 的getXxx方法获取值
				Method method = cls.getMethod(mname);
				cv = contentPutValue(cv, f.getName(), method.invoke(obj));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		db.insert(table, null, cv);
	}
	
	/** 
	 * 插入一个map
	 * @param table
	 * @param obj
	 */
	public void insert(String table, Map<String, Object> obj)
	{
		db = getWritableDatabase();
		ContentValues cv = new ContentValues();
		
		for (String key: obj.keySet()) {
			cv.put(key, obj.get(key).toString());
		}
		db.insert(table, null, cv);
	}
	
	/*
	 * 根据set方法设置bean对象属性值
	 * 此方法待优化
	 */
	private <T> T setObjValue(T obj , Cursor cursor) throws Exception
	{
		int index;
		String mname = null;		//方法名
		Method method = null;		//对应set方法
		String[] cns = cursor.getColumnNames();
		for (String cname: cns) {
			index = cursor.getColumnIndex(cname);
			mname = setMethodName(cname);
			int type = cursor.getType(index);
			
			switch (type) {
				case Cursor.FIELD_TYPE_FLOAT:
					//获取指定参数类型的方法
					method  = obj.getClass().getMethod(mname, float.class);
					method.invoke(obj, cursor.getFloat(index));
					break;
				case Cursor.FIELD_TYPE_BLOB:
					method  = obj.getClass().getMethod(mname, byte[].class);
					method.invoke(obj, cursor.getBlob(index));
					break;
				case Cursor.FIELD_TYPE_INTEGER:
					method  = obj.getClass().getMethod(mname, int.class);
					method.invoke(obj, cursor.getInt(index));
					break;
				case Cursor.FIELD_TYPE_STRING:
					method  = obj.getClass().getMethod(mname, String.class);
					method.invoke(obj, cursor.getString(index));
					break;
				default:
					break;
			}
		}
		return obj;
	}
	
	/*
	 * 查询并返回list,这里仅先实现查询所有
	 */
	public <T> List<T> query(String table, Class<T> cls, String... select)
	{
		StringBuilder query = new StringBuilder("select * from ");
		query.append(table);
		
		List<T> result = new ArrayList<T>();
		db = getReadableDatabase();
		try {
			//实例化一个对象,此bean必须有一个无参数构造方法
			T obj = cls.newInstance();
			//根据查询条件返回查询游标
			Cursor cursor = db.rawQuery(query.toString(), select);
			while (cursor.moveToNext()) {
				//根据set方法设置obj的属性值
				obj = setObjValue(obj, cursor);
				result.add(obj);
			}
		} catch (Exception e) {
			System.out.println("debug:" + e);
		}
		return result;
	}
	
	/*
	 * 更新操作
	 * 根据指定obj属性值更新数据库中信息
	 */
	public void update(String table, Object obj, String where, String[] select,  String... fields)
	{
		db = getWritableDatabase();
		Class<?> cls = obj.getClass();
		ContentValues cv = new ContentValues();
		
		//只更新指定属性字段值
		for (String f: fields) {
			String mname = getMethodName(f);
			try {
				Method method = cls.getMethod(mname);
				cv = contentPutValue(cv, f, method.invoke(obj));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		db.update(table, cv, where, select);
	}
	
	public void execSQL(String sql)
	{
		db = getWritableDatabase();
		db.execSQL(sql);
	}
	
}

一个简单的User对象,拥有几个字段。

private String name;
private int age;
private int id;
private String countries;

Activity代码:

只是布局了4个按钮,用于初始化数据库,插入,更新,demo,没有检测和捕获异常。

public class MainActivity extends Activity {

	private Button create;
	private Button update;
	private Button query;
	private Button insert;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		create = (Button) findViewById(R.id.create);
		update = (Button) findViewById(R.id.update);
		insert = (Button) findViewById(R.id.insert);
		query = (Button) findViewById(R.id.query);
		
		create.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				MySQliteHandler msh = new MySQliteHandler(MainActivity.this, "sqlitdemo", null, 1);
				msh.execSQL("create table user(id integer, name text, age integer, countries text);");
			}
		});
		
		update.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				MySQliteHandler msh = new MySQliteHandler(MainActivity.this, "sqlitdemo", null, 1);
				System.out.println("debug:update");
				User tom = new User("linux", 19, 2, "englist");
				msh.update("user", tom, "id=?", new String[]{"2"} , new String[]{"name", "countries"});
			}
		});
		
		insert.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				MySQliteHandler msh = new MySQliteHandler(MainActivity.this, "sqlitdemo", null, 1);
				System.out.println("debug:insert");
				User tom = new User("tomcat", 19, 2, "china");
				msh.insert("user", tom);
			}
		});
		
		query.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				MySQliteHandler msh = new MySQliteHandler(MainActivity.this, "sqlitdemo", null, 1);
				List<User> list = msh.query("user", User.class);
				User tom = list.get(0);
				System.out.println("debug:query" + tom);
				Toast.makeText(MainActivity.this, tom.toString(), 1000).show();
			}
		});
	}


你可能感兴趣的:(安卓平台使用sqlite)