//创建表
create table person(_id integer primary key autoincrement,name varchar(32),age integer)
//插入数据
insert into person values(1,"bojie",18)
insert into person values(2,"pange",18)
//删除数据
delete from person where name="pange"
//查询数据
select name from person where _id=2
//修改数据
update person set name="pange+tanji" where name="pange"
sqlite
public class MySqliteHelper extends SQLiteOpenHelper {
/**
* version 1
* factory 数据查找的游标 默认null>>> cursor
* name 数据库名
* @param context
*/
public MySqliteHelper(Context context) {
super(context, "my.db", null, 1);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table person (_id integer primary key autoincrement,name varchar(32),age integer)");
}
Dao层
public class PersonService {
private MySqliteHelper helper;
public PersonService(Context context) {
helper = new MySqliteHelper(context);
}
/**
* 插入数据
* @param p
*/
public void insert (Person p){
SQLiteDatabase db = helper.getWritableDatabase();
//db.execSQL("insert into person values("+p.getName()+","+p.getAge()+")");
if(db.isOpen()){
db.execSQL("insert into person(name,age)values (?,?)", new Object[]{p.getName(),p.getAge()});
}
db.close();
}
/**
* 删除数据
* @param name
*/
public void del (String name){
SQLiteDatabase db = helper.getWritableDatabase();
if(db.isOpen()){
db.execSQL("delete from person where name=?", new String[]{name});
}
db.close();
}
/**
* 修改数据
* @param oldName
* @param newName
*/
public void update (String oldName,String newName){
SQLiteDatabase db = helper.getWritableDatabase();
if(db.isOpen()){
db.execSQL("update person set name=? where name=?", new String[]{newName,oldName});
}
db.close();
}
/**
* 查询所有数据
* @return
*/
public List<Person> getAll(){
List<Person> lists=new ArrayList<Person>();
SQLiteDatabase db = helper.getReadableDatabase();
if(db.isOpen()){
Cursor cursor = db.rawQuery("select name ,age from person", null);
if(cursor!=null&&cursor.getCount()>0){
while(cursor.moveToNext()){
String name = cursor.getString(0);
int age = cursor.getInt(1);
Person person=new Person(name, age);
lists.add(person);
}
}
cursor.close();
return lists;
}
db.close();
return null;
}
/**
* 查询对应的数据
* @param id
* @return
*/
public Person getPersonById(int id){
SQLiteDatabase db = helper.getReadableDatabase();
Person person=new Person();
if(db.isOpen()){
Cursor cursor = db.rawQuery("select name,age from person where _id=? ", new String[]{String.valueOf(id)});
if(cursor!=null&&cursor.getCount()>0){
if(cursor.moveToLast()){
String name = cursor.getString(0);
person.setName(name);
int age = cursor.getInt(1);
person.setAge(age);
}
}
cursor.close();
return person;
}
db.close();
return null;
}