SQLiteDatabase db = openOrCreateDatabase("数据库名字.db", Context.MODE_PRIVATE, null);
db.execSQL("DROP TABLE IF EXISTS person");
// 创建person表
db.execSQL("CREATE TABLE person (_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age SMALLINT)")当创建完数据库后就可以使用SQLite了,接下来我们对数据库进行 增、删、改、查操作l了。
增:
代码如下
复制代码
Person person = new Person();
person.setName("john");
person.setAge(19);
// 插入数据
db.execSQL("INSERT INTO person VALUES (NULL, ?, ?)",new Object[] { person.getName(), person.getAge() });
Person person2 = new Person();
person2.setName("john");
person2.setAge(20);
ContentValues cv = new ContentValues();
cv.put("age", person2.getAge()); //修改内容
db.update("person", cv, "name = ?",new String[] { person2.getName() });
查:
代码如下
复制代码
Cursor c = db.rawQuery("select * from person where name=?",new String[]{"john"});
while(c.moveToNext()){
int id =Integer.parseInt(c.getString(c.getColumnIndex("_id")));
String name =c.getString(c.getColumnIndex("name"));
String age = c.getString(c.getColumnIndex("age"));
Log.v("Test ", "id:" + id + " name: " + name + " age: " + age);
}
private class myOnClickListener implements OnClickListener {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_create_database:
db.execSQL("DROP TABLE IF EXISTS person");
// 创建person表
db.execSQL("CREATE TABLE person (_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age SMALLINT)");
break;
case R.id.btn_add:
Person person = new Person();
person.setName("john");
person.setAge(19);
// 插入数据
db.execSQL("INSERT INTO person VALUES (NULL, ?, ?)",
new Object[] { person.getName(), person.getAge() });
break;
case R.id.btn_update:
Person person2 = new Person();
person2.setName("john");
person2.setAge(20);
ContentValues cv = new ContentValues();
cv.put("age", person2.getAge()); //修改内容
db.update("person", cv, "name = ?",
new String[] { person2.getName() });
break;
case R.id.btn_query:
Cursor c = db.rawQuery("select * from person where name=?",new String[]{"john"});
while(c.moveToNext()){
int id = Integer.parseInt(c.getString(c.getColumnIndex("_id")));
String name =c.getString(c.getColumnIndex("name"));
String age = c.getString(c.getColumnIndex("age"));
Log.v("Test ", "id:" + id + " name: " + name + " age: " + age);
}
break;
case R.id.btn_delete:
String whereClause = "_id=?";//删除的条件
String[] whereArgs = {"1"};//删除的条件参数
db.delete("person",whereClause,whereArgs);//执行删除
break;
default:
break;
}
}
}
}
第三步:
代码如下
复制代码
package com.msquirrel.model;
/**
* 实体类
* @author Msquirrel
*
*/
public class Person {
private int _id;
private String name;
private int age;
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}