sqlite操作
首先是创建sqliteOpenHelper的实现类;
需要重写onCreate()
@Override
public void onCreate(sqliteDatabase db) {
db.execsql(CREATE_BOOK);
db.execsql(CREATE_CATEGORY);
Toast.makeText(context,"数据库创建成功",Toast.LENGTH_LONG).show();
}
和onUpgrade()
@Override
public void onUpgrade(sqliteDatabase db,int oldVersion,int newVersion) {
db.execsql("drop table if exists Book");
db.execsql("drop table if exists Category");//增加的表
onCreate(db);
}
两个方法;
onUpgrade()这个方法在数据库更新的时候会自动调用;
public static String CREATE_BOOK="create table Book ( id integer primary key autoincrement,auther text,price real,pages integer,name text )";
上述代码是创建一个数据库中的 Book 表;
添加一个构造方法:
public MyDataBaseHelper(Context context,String name,CursorFactory factory,int version) {
super(context,name,factory,version);
this .context=context;
// TODO Auto-generated constructor stub
}
在MainActivity.class中创建sqliteOpenHelper的实现类;
myDataBaseHelper=new MyDataBaseHelper(this,"BookStore.db",null,3);
参数1代表的是上下文对象
参数2代表的是要创建的数据表的名字
参数3代表的是CursorFactory 一般都写为null
参数4代表的是数据的版本;
增:
sqliteOpenHelper的实现类调用getWritableDatabase()方法得到一个sqliteDataBase对象;
sqliteDatabase db=myDataBaseHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put("name","安卓基础");
values.put("auther","老罗");
values.put("price",57);
values.put("pages",670);
db.insert("Book",null,values);
db.insert("Book",values);
db.delete("Book",null,null);//全部删除了Book表中的数据
改
把作者为老罗的书的价格改成了70;
ContentValues values2=new ContentValues();
values2.put("price",70);
db.update("Book",values2,"auther=?",new String[]{"老罗"});
查
private List<Book> books=new ArrayList<Book>();
...
Cursor cursor=db.query("Book",null);
if (cursor.moveToFirst()) {
books.clear();
do {
Book book=new Book();
String name=cursor.getString(cursor.getColumnIndex("name"));
book.setName(name);
String auther=cursor.getString(cursor.getColumnIndex("auther"));
book.setAuther(auther);
double price=cursor.getDouble(cursor.getColumnIndex("price"));
book.setPrice(price);
int pages=cursor.getInt(cursor.getColumnIndex("pages"));
book.setPages(pages);
books.add(book);
} while (cursor.moveToNext()) ;
}
把Book表中的数据全部读出来;并添加到了一个list集合中;
写了一个Book实体类
public class Book {
private String name;
private String auther;
private int pages;
private double price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuther() {
return auther;
}
public void setAuther(String auther) {
this.auther = auther;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Book [name=" + name + ",auther=" + auther + ",pages=" + pages
+ ",price=" + price + "]";
}
}