您的位置:首页 > 移动开发 > Android开发

Android中SQLite数据库操作(2)——使用SQLiteDatabase提供的方法操作数据库

2013-12-20 12:59 991 查看
如果开发者对SQL语法不熟,甚至以前从未使用过任何数据库,Android的SQLiteDatabase提供了insert、update、delete或query语句来操作数据库。

一、insert方法

long insert(String table, String nullColumnHack, ContentValues values)

table: 代表要插入到的数据表
nullColumnHack: 代表强行插入null值的数据列的列名,当values参数为null,或者不包含任何key_value键值对时该参数有些。
values: 代表一行记录的数据

insert方法插入一条记录使用ContentValue对象封装,ContentValue类似于Map,它提供了put(String key, Object value)方法及getAsXxx(String key)方法。

//创建或打开数据库
db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString()
+ "/my.db", null);
//创建数据表
db.execSQL("create table news_inf(_id integer" +
" primary key autoincrement," +
" news_title varchar(50)," +
" news_content varchar(255))");

//插入数据
ContentValues values = new ContentValues();
values.put("news_title", "title1");
values.put("news_content", "content1");
db.insert("news_inf", null, values);

二、update方法

update(String table, ContentValues values, String whereClause, String[] whereArgs)

table: 代表要更新的表
values: 代表想要更新的数据
whereClause: 满足该whereClause子句的记录将会被更新
whereArgs: 用于为whereClause子句传入参数

该方法返回受此update语句影响的记录条数。

例如:更新上表中_id > 2的 news_title的值。

//更新记录
ContentValues values2 = new ContentValues();
values2.put("news_title", "title1_update");
db.update("news_inf", values2, "_id > ?", new String[]{"2"});


三、delete方法

delete(String table, String whereClause, String[] whereArgs)

tables: 代表要删除的表名
whereClause: 满足该whereClause子句的记录将会被删除
whereArgs:用于为whereClause子句传入参数

该方法返回受此delete子句影响的记录的条数。

同update的使用相同

四、query方法

query(boolean distinct, String table, String[] columns, String whereClause, String[] selectionArgs, String groupBy, Sttring having, String orderBy, String limit)

distinct: 指定是否去除重复记录
table: 查询数据的表名
columns: 要查询的列名
whereClause: 条件查询
whereArgs:条件查询的参数
groupBy: 控制分组
having: 分组过滤
orderBy: 排序
limit: 进行分页

Cursor cursor = db.query("news_inf", new String[]{"news_content, news_title"}, null, null, null, null, null);
while(cursor.moveToNext()){
Toast.makeText(this, cursor.getString(1), 2000).show();
}
cursor.close();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: