SQLite 是android 嵌入式数据库,是典型的关系型数据库,支持我们常用的数据类型,支持标准的sql语句。
SQLite 在嵌入式数据库中经常使用,如词霸中就在sqlite3.dll ,是一个单一文件,不需要安装,就可以直接使用。
在android 系统中我们需要extends 一个抽象类SQLiteOpenHelper 实现它默认的方法。
package com.hkrt.server; import java.util.ArrayList; import java.util.List; import com.hkrt.domain.Person; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class PersonHelper extends SQLiteOpenHelper { private static final String DBNAME="hkrt.db"; private static final String TABLENAME="person"; private static final String ID="id"; private static final String NAME="name"; private static final Integer VERSION=1; public PersonHelper(Context context) { super(context, DBNAME, null, VERSION); } @Override public void onCreate(SQLiteDatabase db) { String sql="create table "+TABLENAME+" ("+ID+" INTEGER primary key autoincrement,"+NAME+" varchar(20))"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } // 添加数据到指定的数据库表中 public long insert(String text){ SQLiteDatabase db =this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(NAME, text); long row = db.insert(TABLENAME, null, values); return row; } //修改指定的数据库表数据 public long update(int id){ SQLiteDatabase db =this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(NAME, "李四"); String where = ID + " = ?"; String[] whereValue = { Integer.toString(id) }; long row= db.update(TABLENAME, values, where, whereValue);//返回受影响的行数标识 return row; } //删除指定数据库中的表数据记录 public long delete(int id){ SQLiteDatabase db = this.getWritableDatabase(); String whereClause=ID+"=?"; String[] whereArgs = { Integer.toString(id) }; long row = db.delete(TABLENAME, whereClause, whereArgs); return row; } //查询列表数据 public List<Person> find(){ List<Person> list = new ArrayList<Person>(); Person person; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.query(TABLENAME, null, null, null, null, null, null); while(cursor.moveToNext()){ person= new Person(); int id = cursor.getInt(0); String name = cursor.getString(1); person.setId(id); person.setName(name); if(person!=null){ list.add(person); } } cursor.close(); db.close(); return list; } }
package com.hkrt.db; import java.util.List; import android.test.AndroidTestCase; import android.util.Log; import com.hkrt.domain.Person; import com.hkrt.server.PersonHelper; public class PersonTest extends AndroidTestCase { String TAG="PersonTest"; public void testCreateDB(){ PersonHelper helper = new PersonHelper(this.getContext()); // helper.getWritableDatabase();// 创建数据库 System.out.println(helper.insert("格林斯")); Log.i(TAG,String.valueOf(helper.insert("google")));//插入新的数据 // System.err.println(helper.update(1));//更新数据 // System.err.println(helper.delete(1));//删除数据 List<Person> persons = helper.find();//查询所有数据 for(Person p:persons){ System.err.println(p.toString()); } // 分页查询是使用和mysql 相同,关键字limit } }
// 添加数据到指定的数据库表中 public long insert(String text){ SQLiteDatabase db =this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(NAME, text); db.beginTransaction();//开始事务 long row; try{ row = db.insert(TABLENAME, null, values); db.setTransactionSuccessful(); }finally{ db.endTransaction(); } return row; }
package com.hkrt.sql; import java.util.ArrayList; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase.CursorFactory; import com.hkrt.domain.User; import com.hkrt.domain.UserEnum; /** * 使用方式:</br> * dbHelper = new DBHelper(this);</br> * dbHelper.open();</br> * 处理数据</br> * dbHelper.close()</br> * @data 2010-11-12 */ public class DBHelper { //sqlite支持NULL Integer real text blob类型,注意该类的所有数据库操作的异常都没有处理 private Context context; private SQLiteDatabase dbInstance; private DBCreator dbCreator; private static final String DB_NAME = "db_user"; private static final int DB_VERSION = 1; public static final String TABLE_NAME="user"; public static final String COLUMN_ID = "user_id"; public static final String COLUMN_NAME="user_name"; public static final String COLUMN_AGE="user_age"; public static final String COLUMN_SEX="user_sex"; public static final String COLUMN_TYPE = "user_type"; private static final String CREATE_TABLE= new StringBuffer().append("Create table ").append(TABLE_NAME) .append(" (") .append(COLUMN_ID).append(" integer primary key,") .append(COLUMN_NAME).append(" varchar(20) not null,") .append(COLUMN_AGE).append(" text not null,") .append(COLUMN_SEX).append(" text not null,") .append(COLUMN_TYPE).append(" integer not null)") .toString(); public DBHelper(Context context) { this.context = context; } public void open() { //第一次,android系统发现数据库没有创建,会调用onCreate方法,以后就只是返回数据库的一个引用 dbCreator = new DBCreator(context,DB_NAME,null,DB_VERSION,CREATE_TABLE,TABLE_NAME); dbInstance = dbCreator.getWritableDatabase(); } public void close() { dbCreator.close(); } public void insert(ContentValues values) { dbInstance.insert(TABLE_NAME, null, values); } public void update(ContentValues values,String whereClause,String[] whereArgs) { dbInstance.update(TABLE_NAME, values, whereClause, whereArgs); } public void delete(String whereClause, String[] whereArgs) { dbInstance.delete(TABLE_NAME, whereClause, whereArgs); } /** * 查询 * @param sql SQL语句,参数用?占位 * @param selectionArgs 参数?的值数组 * @return Cursor游标,注意,和JDBC的ResultSet一样,是在线数据集,所以处理完之前,不能调用close() */ public Cursor query(String sql, String[] selectionArgs) { return dbInstance.rawQuery(sql, selectionArgs); } public ArrayList<User> getQueryAccountList(String sql,String[] args) { ArrayList<User> accoutList = new ArrayList<User>(); open(); Cursor cursor = query(sql, args); while (cursor.moveToNext()) { User user = new User(); user.setId(cursor.getInt(0)); user.setName(cursor.getString(1)); user.setAge(cursor.getString(2)); user.setSex(cursor.getString(3)); user.setType(UserEnum.getUserEnum(cursor.getInt(4))); accoutList.add(user); } //注意游标必须要关闭,否则多查询几次就会出现异常 if(!cursor.isClosed()) { cursor.close(); } close(); return accoutList; } /**通过Id获取唯一user*/ public User getUserById(int id){ User user =null; String sql="select * from "+TABLE_NAME +" where " + COLUMN_ID +" = ?"; ArrayList<User> users = getQueryAccountList(sql,new String[]{String.valueOf(id)}); if(users!=null){ user= new User(); user.setId(users.get(0).getId()); user.setName(users.get(0).getName()); user.setAge(users.get(0).getAge()); user.setSex(users.get(0).getSex()); user.setType(users.get(0).getType()); } return user; } /** * 模糊查询 */ public ArrayList<User> getQueryAccountListLike(String str){ ArrayList<User> accoutList = new ArrayList<User>(); open(); StringBuffer sb = new StringBuffer(); sb.append("select * from ").append(TABLE_NAME).append(" where ").append(COLUMN_NAME).append(" like ").append("'"+str +"%'"); Cursor cursor = dbInstance.rawQuery(sb.toString(), new String[]{}); while (cursor.moveToNext()) { User user = new User(); user.setId(cursor.getInt(0)); user.setName(cursor.getString(1)); user.setAge(cursor.getString(2)); user.setSex(cursor.getString(3)); user.setType(UserEnum.getUserEnum(cursor.getInt(4))); accoutList.add(user); } //注意游标必须要关闭,否则多查询几次就会出现异常 if(!cursor.isClosed()) { cursor.close(); } close(); return accoutList; } private class DBCreator extends SQLiteOpenHelper { private Context context; private String createTableSql; private String tableName; public DBCreator(Context context, String dbname, CursorFactory factory, int version,String createTableSql,String tableName) { super(context, dbname, factory, version); this.context = context; this.createTableSql = createTableSql; this.tableName = tableName; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(createTableSql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("drop table if exists "+tableName); onCreate(db); } } }