建一个基础的类,新建一个数据库
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();
}
}