码迷,mamicode.com
首页 > 其他好文 > 详细

ContentValues的使用

时间:2016-01-19 18:52:21      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

技术分享技术分享

建一个基础的类,新建一个数据库
package com.example.ContentValuesDemo;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DemoHelper extends SQLiteOpenHelper {
public DemoHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table stu (id integer primary key autoincrement,name text not null,age text not null)");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

db.execSQL("drop table if exists stu");
onCreate(db);

}
}


使用contentValues写方法:直接用db的insert,delete,update方法。id用占位符...

package com.example.ContentValuesDemo;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;

/**
* Created by Anonymous on 2016/1/19.
*/
public class DemoMethods {

private SQLiteDatabase db;
private static final String DataName = "stu";

public DemoMethods(SQLiteDatabase db) {
this.db = db;
}

public void insertData(String name,String age){

ContentValues cv = new ContentValues();
cv.put("name", name);
cv.put("age",age);
db.insert(DataName, null, cv);

}

public void deleteData(int id ){
String whereCause = "id=?";
String[] whereArgs = new String[]{String.valueOf(id)};
ContentValues cv = new ContentValues();
db.delete(DataName, whereCause, whereArgs);
}

public void updataData(int id,String name,String age){

String whereCause = "id=?";
String[] whereArgs = new String[]{String.valueOf(id)};

ContentValues cv = new ContentValues();
cv.put("name", name);
cv.put("age", age);
db.update(DataName, cv, whereCause, whereArgs);

}
}

mainActivity引用:
package com.example.ContentValuesDemo;

import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

public class MyActivity extends Activity {


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

DemoHelper helper = new DemoHelper(MyActivity.this, "stu.db", null, 1);

SQLiteDatabase db = helper.getWritableDatabase();

DemoMethods methods = new DemoMethods(db);

for (int i = 0; i < 5; i++) {

methods.insertData("mary" + i, "55");
}

for (int i = 1; i < 3; i++) {

methods.deleteData(i);
}
methods.updataData(3, "change", "100");
db.close();
}
}




ContentValues的使用

标签:

原文地址:http://www.cnblogs.com/share2015/p/5142813.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!