利用sql语句对数据库进行操作

public void savePerson(Person p)
{
String sql = " insert into person(name,age) values(?,?);";

SQLiteDatabase db = helper.getWritableDatabase();

//db代表的是一个数据库的一个连接
if(db.isOpen()) //判断数据库是否打开
{
List list = new ArrayList();
for(int i=0; i < 20; i++)
{
list.add(new Person(i,"zs" + i,i));
}

for(Person person : list)
{
db.execSQL(sql, new Object[]{person.getName(),person.getAge()}); // 向数据库里面去添加一行记录

}

db.close(); // 记住一定要关闭数据库的连接
}

}

/**
* 删除一个对象
* sql:delete from person where _id = 1;
*/
public void deletePerson(Integer id)
{
String sql = " delete from person where _id = ?;";

SQLiteDatabase db = helper.getWritableDatabase();

if(db.isOpen())
{
db.execSQL(sql, new Integer[]{id});

db.close();
}
}

/**
* 修改一个对象
* sql:update person set name ='cccc' where _id=1;
*/
public void updatePerson(Person p)
{
String sql = " update person set name =? where _id=?;";

SQLiteDatabase db = helper.getWritableDatabase();

if(db.isOpen())
{
db.execSQL(sql, new Object[]{p.getName(),p.get_id()});

db.close();
}
}

/**
* 查询所有
*/
public List queryPerson()
{
String sql = " select _id,name,age from person;";
SQLiteDatabase db = helper.getReadableDatabase();
List list = null;

if(db.isOpen())
{
Cursor cursor = db.rawQuery(sql, null); //查询

//cursor.getCount() 查看执行sql以后返回的结果集的个数
if(null != cursor && cursor.getCount() > 0)
{
list = new ArrayList();

while(cursor.moveToNext())
{
Integer id = cursor.getInt(0);
String name = cursor.getString(1);
Integer age = cursor.getInt(2);

list.add(new Person(id,name,age));
}

}

}
return list;
}

你可能感兴趣的:(android)