SQLite数据库的添删改查
还是那句话,经常重复的代码要总结起来
1.首先建一个person实例:
Person.java
package morgen.domain;
public class Person {
private Integer id;
private String name;
private String phone;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Person(Integer id, String name, String phone) {
this.id = id;
this.name = name;
this.phone = phone;
}
public Person(String name, String phone) {
this.name = name;
this.phone = phone;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", phone=" + phone + "]";
}
}
2.接着创建数据库文件和表
DBOpenHelper.java
package morgen.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBOpenHelper extends SQLiteOpenHelper {
public DBOpenHelper(Context context) {
super(context, "morgen.db", null, 2);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE person(id integer primary key autoincrement, name varchar(20))");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("ALTER TABLE person ADD phone VARCHAR(12) NULL");
}
}
3.对数据库进行操作
PersonService.java
package morgen.service;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import morgen.db.DBOpenHelper;
import morgen.domain.Person;
public class PersonService {
private DBOpenHelper dbOpenHelper;
public PersonService(Context context){
dbOpenHelper = new DBOpenHelper(context);
}
/**
* 保存数据
* @param person
*/
public void save(Person person){
&n
相关新闻>>
- 发表评论
-
- 最新评论 更多>>