1,SQLite 简单使用
1,SQLite支持的数据类型
NULL. The value is a NULL value.
INTEGER. The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.
REAL. The value is a floating point value, stored as an 8-byte IEEE floating point number.
TEXT. The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16LE).
BLOB. The value is a blob of data, stored exactly as it was input.
2,相关数据库定义数据类型词与SQLite数据类型的关联表
Example Typenames From The
CREATE TABLE Statement
or CAST ExpressionResulting Affinity Rule Used To Determine Affinity INT
INTEGER
TINYINT
SMALLINT
MEDIUMINT
BIGINT
UNSIGNED BIG INT
INT2
INT8INTEGER 1 CHARACTER(20)
VARCHAR(255)
VARYING CHARACTER(255)
NCHAR(55)
NATIVE CHARACTER(70)
NVARCHAR(100)
TEXT
CLOBTEXT 2 BLOB
no datatype specifiedNONE 3 REAL
DOUBLE
DOUBLE PRECISION
FLOATREAL 4 NUMERIC
DECIMAL(10,5)
BOOLEAN
DATE
DATETIMENUMERIC 5 把数据类型搞定了…我们就开始使用我们的android的sqlite了…
第一步:实现一个SQLiteOpenHelper类
//创建一个继承SQLiteOpenHelper类 public class MyOpenHelper extends SQLiteOpenHelper { //必须实现的一个构造方法 public MyOpenHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); // TODO Auto-generated constructor stub } //设置数据库初始化版本号 private static final int DATABASE_VERSION = 1; //设置数据库创建的表名 private static final String TABLE_NAME = "users"; //构建创建表的 SQL 的语句 private static final String TABLE_CREATE_SQL = "CREATE TABLE " + TABLE_NAME+"(id INTEGER primary key,name TEXT)"; //自定义构造方法传入content,与数据库名字 public MyOpenHelper(Context context,String name){ this(context,name,null,DATABASE_VERSION); } //自定义构造方法传入用来升级数据库的版本号 public MyOpenHelper(Context context,String name,int version){ this(context,name,null,version); } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub Log.d("sqlite","sql-->CreateTable"+ TABLE_CREATE_SQL); db.execSQL(TABLE_CREATE_SQL); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub } }ok
第二步:使用MyOpenHelper
//某onclick方法中实现String dataBaseName = "employee"'; MyOpenHelper moh = new MyOpenHelper(Sqlite_contentproviderActivity.this,dataBaseName ); SQLiteDatabase sdb = moh.getReadableDatabase(); toastSQL = Toast.makeText(context, "创建数据库成功", Toast.LENGTH_LONG); toastSQL.show();1,我们到adb 中查看在设备中我们保存的数据库文件在
cd /data/data/<package_name>/databases
2,ls 命令看下
3,用sqlite3命令进入数据库
这样我们就看到我们刚才创建的表了…
这里给出插入操作的代码
String databaseName = "employee"; MyOpenHelper moh = new MyOpenHelper(Sqlite_contentproviderActivity.this, databaseName); //获取一个可写操作 SQLiteDatabase sdb = moh.getWritableDatabase(); ContentValues cv = new ContentValues(); String[] name = {"tom","achai","nevin","week"}; for (int i = 0; i < name.length; i++) { cv.put("name", name[i]); sdb.insert("users", null, cv); }剩下的操作…请阅读官方文档SQLiteDatabase里面的方法
2,创建属于自己的content provider
1,建立一个属于自己的content provider你必须要做
- 设置一个存储数据的地方,可以使用android 提供的文件存储方法,或者使用SQLite databases,然而,你可以存储任何你想要的数据,android提供的SQLiteOpenHelper可以帮助你创建属于和管理你自己的数据库,
- 实现ContentProvider 提供用于访问数据的类
- 在AndroidManifest.xml,声明你的 content provider
2,编写一个数据工具类
public class ContentProviderData { public static final String AUTHORIY = "kg.tom.FirstProvider";public class ContentProviderData { //定义我们provider使用的认证uri public static final String AUTHORIY = "kg.tom.FirstProvider"; //定义我们数据库的名字 public static final String DATABASE_NAME = "kg_tom_pro_test"; //定义数据库的版本号 public static final int DATABASE_VERSION = 1; //定义创建表的名字 public static final String USERS_TABLE_NAME = "users" ; //实现BaseColums,自带两列,_id,_count public static final class UserTableMetaData implements BaseColumns{ //定义创建表的名字 public static final String TABLE_NAME = "users"; //定义provider的uri public static final Uri CONTENT_URI = Uri.parse("content://"+AUTHORIY + "/users"); //定义一条数据的类型 public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.firstprovider.user"; //定义一组数据的类型 p ublic static final String CONTENT_TYPE_ITEM = "vnd.android.cursor.item/vnd.firsstprovider.user"; //定义列名 public static final String USER_NAME = "name"; //定义排序规则 public static final String DEFULT_SORT_ORDER = "_id desc"; } }2,继承content provider 类
继承这个类我们同时要实现以下几个方法:
query()
insert()
update()
delete()
getType()
onCreate()
还有必须添加一个UriMatcher对象
关于UriMatcher对象的使用文档有很好的解释
//定义URI标识符,数值定义请参考文档 public static final int INCOMING_USER_COLLECTION = 1; public static final int INCOMING_USER_SINGLE = 2; //定义UriMatcher对象 public static final UriMatcher uMatcher; //把标识符加入到URI中,固定写法 static{ uMatcher = new UriMatcher(UriMatcher.NO_MATCH); //第一个参数为content provider authoriy uMatcher.addURI(AUTHORIY, "users", INCOMING_USER_COLLECTION); uMatcher.addURI(AUTHORIY, "users/#", INCOMING_USER_SINGLE); }一个完整的content provider
public class FirstProvider extends ContentProvider { //定义URI标识符 public static final int INCOMING_USER_COLLECTION = 1; public static final int INCOMING_USER_SINGLE = 2; //定义UriMatcher对象 public static final UriMatcher uMatcher; //把标识符加入到URI中,固定写法 static{ uMatcher = new UriMatcher(UriMatcher.NO_MATCH); uMatcher.addURI(ContentProviderData.AUTHORIY, "users", INCOMING_USER_COLLECTION); uMatcher.addURI(ContentProviderData.AUTHORIY, "users/#", INCOMING_USER_SINGLE); } //这里是定义查询用的列名的别名 public static HashMap<String , String> userMap; private DataBaseHelper dh; static{ userMap = new HashMap<String, String>(); userMap.put(UserTableMetaData._ID, "id"); userMap.put(UserTableMetaData.USER_NAME, UserTableMetaData.USER_NAME); } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { // TODO Auto-generated method stub return 0; } //根据传入的URI @Override public String getType(Uri uri) { // TODO Auto-generated method stub Log.d("sqlite", "getType-->"); switch(uMatcher.match(uri)){ case INCOMING_USER_COLLECTION: return UserTableMetaData.CONTENT_TYPE; case INCOMING_USER_SINGLE: return UserTableMetaData.CONTENT_TYPE_ITEM; default: throw new IllegalArgumentException("unKnown uri" + uri); } } @Override public Uri insert(Uri uri, ContentValues values) { // TODO Auto-generated method stub Log.d("insert", "class" + getClass()); Log.d("insert", "content" + getContext()); SQLiteDatabase db = dh.getWritableDatabase(); long rowId = db.insert(UserTableMetaData.TABLE_NAME, null, values); if(rowId > 0){ Uri insertUri = ContentUris.withAppendedId(UserTableMetaData.CONTENT_URI, rowId); getContext().getContentResolver().notifyChange(insertUri, null); return insertUri; } return null; } @Override public boolean onCreate() { // TODO Auto-generated method stub Log.d("sqlite", "createPro--->"); dh = new DataBaseHelper(getContext(), ContentProviderData.DATABASE_NAME); // SQLiteDatabase db = dh.getReadableDatabase(); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // TODO Auto-generated method stub SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); switch(uMatcher.match(uri)){ case INCOMING_USER_COLLECTION: qb.setTables(UserTableMetaData.TABLE_NAME); qb.setProjectionMap(userMap); break; case INCOMING_USER_SINGLE: qb.setTables(UserTableMetaData.TABLE_NAME); qb.setProjectionMap(userMap); qb.appendWhere(UserTableMetaData._ID+ "=" + uri.getPathSegments().get(1) ); break; } String orderBy; if(TextUtils.isEmpty(sortOrder)){ orderBy = UserTableMetaData.DEFULT_SORT_ORDER; }else{ orderBy = sortOrder; } SQLiteDatabase db = dh.getWritableDatabase(); Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder); c.setNotificationUri(getContext().getContentResolver(), uri); Log.d("sqlite", "first--->>"); return c; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // TODO Auto-generated method stub return 0; } }3,在activity中的方法中用上这几行代码就可以进行插入
//定义插入用数据的对象,本质是一个map ContentValues values = new ContentValues(); //键,值对 values.put("id", 1); //定义表名 String name = ContentProviderData.USERS_TABLE_NAME; //键值对 values.put(ContentProviderData.UserTableMetaData.USER_NAME, "tom"); //进行content provider 的插入操作 Uri uri = getContentResolver().insert( ContentProviderData.UserTableMetaData.CONTENT_URI, values);至于剩下的
query()
delete()
自己参照文档补全吧